{{announcement.body}}
{{announcement.title}}

What Are Laravel Resource Controllers?

DZone 's Guide to

What Are Laravel Resource Controllers?

In this article, we discuss some basics behind what Laravel Resource Controllers are and set you up to use them in your next project.

· Web Dev Zone ·
Free Resource

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 create 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. a 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

PHP


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.

PHP


Conclusion

I hope your doubts about what Laravel Resource Controllers are have been cleared and that you feel confident 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.

Topics:
laravel, php, resource controller, tutorial, web dev

Published at DZone with permission of Adi Sk . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}