Tổng kết - Laravel

Tổng kết - Laravel

  • Nội dung này sẽ tổng kết lại các bài học về Insert - View - Detail - Update - Delete.
  • Cấu trúc folder của các file được tạo như sau:

myproject

Nội dung các file

/app/Http/Controllers/Admin/AdminNewsController.php

File Controller chứa các function xử lý: Insert - View - Detail - Update - Delete.

<?php

namespace App\Http\Controllers\Admin;

use App\News;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class AdminNewsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $news = DB::table('news')->select('*');
        $news = $news->get();
        $pageName = 'Tên Trang - News';

        return view('/admin/news', compact('news', 'pageName'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('/admin/news_create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $news = new News;
        $news->title = $request->title; 
        $news->email = $request->email;
        $news->description = $request->description;

        $news->save();
        return redirect()->action('Admin\AdminNewsController@create');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $news = News::where('id', '=', $id)->select('*')->first();
        $des = html_entity_decode($news->description);
        return view('/admin/news_detail', compact('news', 'des'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $news = News::findOrFail($id);
        $pageName = 'News - Update';
        return view('/admin/news_update', compact('news', 'pageName'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $news = News::find($id);
        $news->title = $request->title;
        $news->email = $request->email;
        $news->description = $request->description;

        $news->save();
        return redirect()->action('Admin\AdminNewsController@index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $news = News::find($id);

        $news->delete();
        return redirect()->action('Admin\AdminNewsController@index')->with('success','Dữ liệu xóa thành công.');
    }
}

/app/News.php

Model News dùng để khai báo table news.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class News extends Model
{
    protected $table='news';
}

/resources/views/admin/news_create.blade.php

Trang view - insert dữ liệu.

<form method="post" action="/admin/news/store">
    @method('PATCH')
    @csrf
    <p>
        <label for="title">Title</label><br>
        <input type="text" name="title" value="">
    </p>

    <p>
        <label for="email">Email</label><br>
        <input type="text" name="email" value="">
    </p>

    <p>
        <label for="description">Description</label><br>
        <textarea cols="20" rows="10" name="description"></textarea>
    </p>

    <p>
        <button type="submit">Submit</button>
    </p>
</form>

/resources/views/admin/news.blade.php

Trang view - hiển thị danh sách dữ liệu.

<h1>{{ $pageName }}</h1>
<table border="1">
    <thead>
        <tr>
            <th>ID</th>
            <th>Title</th>
            <th>Email</th>
            <th>Tools</th>
        </tr>
    </thead>
    <tbody>
        @foreach($news as $row)
        <tr>
            <td>{{$row->id}}</td>
            <td>{{$row->title}}</td>
            <td>{{$row->email}}</td>
            <td><a href="/admin/news/edit/{{$row->id}}">Edit</a><br>
                <form method="POST" action="/admin/news/delete/{{$row->id}}" onsubmit="return ConfirmDelete( this )">
                    @method('DELETE')
                    @csrf
                    <button type="submit">Delete</button>
                </form>
            </td>
        </tr>
        @endforeach
    </tbody>
</table>

/resources/views/admin/news_detail.blade.php

Trang view - hiển thị chi tiết dữ liệu.

<h1>News</h1>

<h2>{{ $news->title }}</h2>
<p>{{ $news->email }}</p>
<div>{!! $des !!}</div>

/resources/views/admin/news_update.blade.php

Trang view - update dữ liệu.

<h1>{{ $pageName }}</h1>
<form method="post" action="/admin/news/update/{{ $news->id }}">
    @method('PATCH')
    @csrf
    <input type="hidden" name="id" value="{{ $news->id }}">
    <p>
        <label for="title">Title</label><br>
        <input type="text" name="title" value="{{ $news->title }}">
    </p>

    <p>
        <label for="email">Email</label><br>
        <input type="text" name="email" value="{{ $news->email }}">
    </p>

    <p>
        <label for="description">Description</label><br>
        <textarea cols="50" rows="5" name="description">{{ $news->description }}</textarea>
    </p>

    <p>
        <button type="submit">Submit</button>
    </p>
</form>

/routes/web.php

File điều khiển Route.

Route::get('/admin/news/create', 'Admin\AdminNewsController@create');
Route::patch('/admin/news/store', 'Admin\AdminNewsController@store');
Route::get('/admin/news', 'Admin\AdminNewsController@index');
Route::get('/admin/news/{id}', 'Admin\AdminNewsController@show');
Route::get('/admin/news/edit/{id}', 'Admin\AdminNewsController@edit');
Route::PATCH('/admin/news/update/{id}', 'Admin\AdminNewsController@update');
Route::DELETE('/admin/news/delete/{id}', 'Admin\AdminNewsController@destroy');

Thông thường các Route có cùng chung một nhóm, sẽ được group lại để dễ quản lý và source code của Route nhìn cũng gọn hơn, Chúng ta có thể viết lại Route như sau:

Route::group(['prefix'=>'/admin'],function(){
    Route::get('news/create', 'Admin\AdminNewsController@create');
    Route::PATCH('news/store', 'Admin\AdminNewsController@store');
    Route::get('news', 'Admin\AdminNewsController@index');
    Route::get('news/{id}', 'Admin\AdminNewsController@show');
    Route::get('news/edit/{id}', 'Admin\AdminNewsController@edit');
    Route::PATCH('news/update/{id}', 'Admin\AdminNewsController@update');
    Route::DELETE('news/delete/{id}', 'Admin\AdminNewsController@destroy');
});

Nội dung bài học Insert - View - Detail - Update - Delete, chúng ta chỉ chú trọng cách trình bày sao cho người học hiểu rõ cách hoạt động ra sao, đã bỏ qua một vài thao tác cần thiết khác: validate form, middleware cho trang Admin, các bạn có thể xem lại 2 phần học validate formmiddleware để bổ sung thêm nhé.