What are Laravel Resource Controllers
Adi · 25/Mar/20
Hi all, this is Adi again for a Laravel post. I recently found a lot of questions on StackOverflow asking what Laravel Resource controllers were. I wanted to explain this basic concept. Read on.
Laravel Resource Controller
Resource controllers are just Laravel controllers with all the methods to create, read, update and delete a resource (or a Model). You can create a resource controller with this artisan
command
php artisan make:controller PhotoController --resource
This command will create a PhotoController.php
in your controller directory and will have automatically created 7 methods index
, show
, create
, store
, edit
, update
, destroy
. All these methods will be empty, you will have to fill them with the logic for each action. By default, when you execute the command, Laravel will use the model name from the controller, eg. Photo
model will be used for PhotoController
, if you want to use a different model you could use
php artisan make:controller PhotoController --resource --model=Photo
Now the new controller will you what you mention in the --model
flag.
You could also create controllers for your API routes using the --api
flag instead of --resource
flag. This will create all the methods except the create
and edit
methods, as they are not required for an api call.
Laravel Resource Route
Laravel also provides an easy way to make routes for Resource controllers using
Route::resource('photos', 'PhotoController');
// GET /photos PhotoController@index
// GET /photos/create PhotoController@create
// POST /photos PhotoController@store
// GET /photos/{id} PhotoController@show
// GET /photos/{id}/edit PhotoController@edit
// PUT /photos/{id} PhotoController@update
// DELETE /photos/{id} PhotoController@destory
This method will create all the 7 routes needed to access each action from the browser. You could customize this to create only certain routes you need or leave what you don’t need like so.
Route::resource('photos', 'PhotoController')->only(['index', 'show']);
Route::resource('photos', 'PhotoController')->except(['create', 'store', 'update', 'destroy']);
Conclusion
I hope your doubts about what Laravel Resources controller have been cleared and may want to try this in your next project. Hope this small piece helped you understand them a little better.
For more information, you could look up the docs.
That’s all for now, this has been Adi.
If you are looking for a Freelance Web Developer you can contact me