Laravel Restful Resource Controller

July, 5 2020 PHP Laravel

Frameworks get better overnight, but its users are usually lazy to go back to daily learn these improvements and usually will continue to use the framework the way they first learnt them unless breaking changes are introduced.

Resource controllers make it simple and easy to build RESTful controllers around resources. For instance, you may wish to create a controller that handles HTTP requests regarding "posts" stored by your application. Using the make:controller Artisan command, we can quickly create such a controller:

php artisan make:controller PostController --resource

The Artisan command will generate a controller file at app/Http/Controllers/PostController.php controller that contain a method for each of the available resource operations as seen in the table below.

Verb Path Action Route Name
GET /post index post.index
GET /post/create create post.create
POST /post store post.store
GET /post/{post} show post.show
GET /post/{post}/edit edit post.edit
PUT/PATCH /post/{post} update post.update
DELETE /post/{post} destroy post.destroy


Next, you may register a resourceful route to the controller in your routes/api.php or routes/web.php file:

Route::resource('post', 'PostController');

This single registration will remove the need for you to create different route registrations for GET, POST, PUT, DELETE and the rest of the HTTP methods as usually done.

In an event you would not want all the HTTP methods, you can use either of the only or except assertions as seen below,

Route::resource('post', 'PostController', ['only' => 
  ['index', 'show']
]);
  
Route::resource('post', 'PostController', ['except' => 
  ['create', 'store', 'update', 'destroy'
]]);

For convenience, you may also find the apiResource interesting as it excludes routes that present HTML templates such as create and edit.

To quickly generate an API resource controller that does not include the create or edit methods, use the --api switch when executing the make:controller command:

php artisan make:controller API/PostController --api

And then register a resourceful route to the controller in your routes/api.php or routes/web.php file:

Route::apiResource('post', 'PostController');

You can read more about the Laravel Resource Controller on the official Laravel website at https://laravel.com/docs/5.2/controllers

I'd love to hear your thoughts. Let me know in the comments section on twitter or on LinkedIn


By Nuhu Ibrahim

Full Stack Web and Desktop Developer