Search code examples
phplaravellaravel-routing

Ways to write Laravel routes


Is there a better way to write these routes? It seems I am repeating the same controller in my route files.

Route::post('user', [UserController::class, 'update']);
Route::get('user', [UserController::class, 'index']);
Route::delete('users/{id}',[UserController::class, 'destroy']);  

Solution

  • You can use a resource route, where you specify a subset of actions in the controller.

    Route::resource('user', UserController::class)->only([
        'index', 'update', 'destroy'
    ]);
    

    You can also use the --model option when generating a controller with the stubbed out CRUD methods.

    php artisan make:controller UserController --resource --model=User
    

    Result:

    +-----------+-------------+--------------+---------------------------------------------+------------+
    | Method    | URI         | Name         | Action                                      | Middleware |
    +-----------+-------------+--------------+---------------------------------------------+------------+
    | GET|HEAD  | user        | user.index   | App\Http\Controllers\UserController@index   | web        |
    | PUT|PATCH | user/{user} | user.update  | App\Http\Controllers\UserController@update  | web        |
    | DELETE    | user/{user} | user.destroy | App\Http\Controllers\UserController@destroy | web        |
    +-----------+-------------+--------------+---------------------------------------------+------------+