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

9 Mẹo lập trình Web “ẩn mình” giúp tiết kiệm hàng giờ đồng hồ

Hầu hết các lập trình viên (kể cả những người giỏi) đều tốn thời gian x

Can GPT-4o Generate Images? All You Need to Know about GPT-4o-image

OpenAI‘s GPT-4o, introduced on March 25, 2025, has revolutionized the way we create visual con

Khi nào nên dùng main, section, article, header, footer, và aside trong HTML5

HTML5 đã giới thiệu các thẻ ngữ nghĩa giúp cấu trúc nội dung web một cách có

So sánh Webhook và API: Khi nào nên sử dụng?

Trong lĩnh vực công nghệ thông tin và phát triển phần mềm, Webhook và API là hai th