Cách tạo Resource Controller trong Laravel

Trong bài viết này, mình sẽ chia sẻ cách sử dụng resource controller bằng cách sử dụng resource route trong ứng dụng laravel 5, laravel 6, laravel 7 và laravel 8. Laravel resource controller là tính năng khá thú vị để tạo ứng dụng CRUD nhanh chóng trong laravel. Bình thường khi mình tạo ứng

Trong bài viết này, mình sẽ chia sẻ cách sử dụng resource controller bằng cách sử dụng resource route trong ứng dụng laravel 5, laravel 6, laravel 7 và laravel 8.
Laravel resource controller là tính năng khá thú vị để tạo ứng dụng CRUD nhanh chóng trong laravel.
Bình thường khi mình tạo ứng dụng CRUD mình sẽ phải truy cập vào route và mất thời gian khai báo các routes insert, update, view, delete như bên dưới.

CRUD Route:

Route::get('items',['as'=>'items.index','uses'=>'[email protected]']);Route::post('items/create',['as'=>'items.store','uses'=>'[email protected]']);Route::get('items/edit/{id}',['as'=>'items.edit','uses'=>'[email protected]']);Route::patch('items/{id}',['as'=>'items.update','uses'=>'[email protected]']);Route::delete('items/{id}',['as'=>'items.destroy','uses'=>'[email protected]']);Route::get('items/{id}',['as'=>'items.view','uses'=>'[email protected]']);

Resource Route:

Với khai báo routes ở trên, mình sẽ phải tạo 6 routes cho ứng dụng CRUD. Nhưng mình sẽ tạo 6 routes đó bằng cách sử dụng resource route bên dưới:

Route::resource('items', 'ItemController');

Bây giờ, mình có thể chạy lệnh dưới đây và kiểm tra tạo danh sách routes:

php artisan route:list

Output:


+--------+-----------+---------------------+-----------------------------+------------------------------------------------------------+------------------------------------------+
| Domain | Method    | URI                 | Name                        | Action                                                     | Middleware                               |
+--------+-----------+---------------------+-----------------------------+------------------------------------------------------------+------------------------------------------+
|        | GET|HEAD  | /                   | generated::XBEZcUfEGj63UYJf | Closure                                                    | web                                      |
|        | GET|HEAD  | api/user            | generated::i9vdaYkfbCjVyzB1 | Closure                                                    | api                                      |
|        |           |                     |                             |                                                            | AppHttpMiddlewareAuthenticate:sanctum |
|        | GET|HEAD  | items               | items.index                 | AppHttpControllers[email protected]                  | web                                      |
|        | POST      | items               | items.store                 | AppHttpControllers[email protected]                  | web                                      |
|        | GET|HEAD  | items/create        | items.create                | AppHttpControllers[email protected]                 | web                                      |
|        | GET|HEAD  | items/{item}        | items.show                  | AppHttpControllers[email protected]                   | web                                      |
|        | PUT|PATCH | items/{item}        | items.update                | AppHttpControllers[email protected]                 | web                                      |
|        | DELETE    | items/{item}        | items.destroy               | AppHttpControllers[email protected]                | web                                      |
|        | GET|HEAD  | items/{item}/edit   | items.edit                  | AppHttpControllers[email protected]                   | web                                      |
|        | GET|HEAD  | sanctum/csrf-cookie | generated::aARefmQCMyRZY8wA | LaravelSanctumHttpControllers[email protected] | web                                      |
+--------+-----------+---------------------+-----------------------------+------------------------------------------------------------+------------------------------------------+

Tiếp theo mình sẽ tạo resource controller bằng cách sử dụng command bên dưới,và kiểm tra ItemController trong thư mục app.

Resource Controller Command:

php artisan make:controller ItemController --resource --model=Item

Sau khi chạy thành công lệnh trên, bạn có thể thấy ItemController của mình với phương thức resource sau.

app/Http/Controllers/ItemController.php

<?php

namespace AppHttpControllers;

use AppModelsItem;
use IlluminateHttpRequest;

class ItemController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return IlluminateHttpResponse
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  AppModelsItem  $item
     * @return IlluminateHttpResponse
     */
    public function show(Item $item)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  AppModelsItem  $item
     * @return IlluminateHttpResponse
     */
    public function edit(Item $item)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  AppModelsItem  $item
     * @return IlluminateHttpResponse
     */
    public function update(Request $request, Item $item)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  AppModelsItem  $item
     * @return IlluminateHttpResponse
     */
    public function destroy(Item $item)
    {
        //
    }
}

Với cách này bạn có thể đơn giản sử dụng resource route và controller, để tạo nhanh chức năng CRUD trong ứng dụng của bạn.

Nguồn: viblo.asia

Bài viết liên quan

Mình đang dùng Google Domains để check tên miền hàng ngày

Từ khi thông báo dịch vụ Google Domains bỏ mác Beta, mình mới để ý và bắt đầ

Cách sử dụng SFTP (Giao thức truyền file qua SSH an toàn hơn)

SFTP là cách an toàn để truyền files giữa các máy tính, gữa máy local và web hostin

Hotlinking: Key Reasons to Avoid and Methods to Protect Your Site

Hotlinking might seem an easy way to acquire website assets, but in reality, it brings several disad

Sự Khác Nhau Giữa Domain và Hosting Là Gì?

Sự khác nhau giữa domain và hosting là gì? Bài này giải thích ngắn và dễ hiểu nh