Route Resource in Laravel 5.1

Access all tutorials in sprocket icon.

August 15, 2015 from author Bill Keck.

How to create a route resource in Laravel 5.1

This tutorial builds on the model creation tutorial, so you might want to look at that as well.

Laravel has excellent documentation on routing, so I won’t go over it all here. You can also check out great free videos on Laracasts on routes.

But I do want to cover a basic route resource in case you are following along in some of the other tutorials, especially the one where we are making a generic Widget model. I’m calling it Widget because I need something generic for demonstration purposes.

Ok, so let’s create a route resource, this is going to be really difficult. Go to app/Http/routes.php and open it, then add the following route:



Route::resource('widget', 'WidgetController');

Ok, so not really difficult, in fact it’s just one line. Now if you have not created a WidgetController, it will complain when you try to run at the command line:



php artisan route:list

So if you have not created WidgetController, let’s do so now, using artisan from the command line:



php artisan make:controller WidgetController

And just like that we have our controller. But we’re not going to focus on that, since this is a tutorial about route resource.

Anyway, if you now run from the command line:



php artisan route:list

You can see you have 8 routes, which map perfectly to the restful WidgetController. So with this one line of code, we will be able to go to our create, store, edit, update, destroy, show, and index methods on the controller.

You can see the different types of requests. Create, for example, is get. This will simply return a view that displays a form. The store route is a post request. This method on the controller will accept the form post from the create page and store it in the DB.

The edit route is a get request and the controller returns the edit form. The update route is a post request and maps to the update method on the controller, which will store the changes in the DB. The destroy route sends us to the destroy method and that is for deleting records.

The show and index routes are get requests. Index is typically used to return a list of results and show is for individual records.

This is just a brief introduction. I really recommend the Laracast’s video on routing and the Laravel docs for more info. What we did here is just enough to get started.

I hope you have enjoyed this tutorial and found it useful. Click on the sprocket icon at the top of the page to see all tutorials.

Please comment, share, and like if you can, thanks!

I don’t have a donate button, but If you would like to support my work and learn more about Laravel, you can do so by buying one of my books, Laraboot: laravel 5* For Beginners, I really appreciate it.