Skip to content
Advertisement

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']);  

Advertisement

Answer

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   | AppHttpControllersUserController@index   | web        |
| PUT|PATCH | user/{user} | user.update  | AppHttpControllersUserController@update  | web        |
| DELETE    | user/{user} | user.destroy | AppHttpControllersUserController@destroy | web        |
+-----------+-------------+--------------+---------------------------------------------+------------+
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement