Laravel gives you many ways to do things. With controllers, it is no different. We saw that we can use explicit controller routing already, and now we are going to see that we can also implement Resourceful Routing with our controllers. There are a lot of benefits to using resrouceful routing. The main benefit, is that by following convention over configuration, we’ll be able to write less code using restful methods, yet have as much or more functionality than we did before. Let’s check it out!

What is REST?

First up, let’s talk about rest or representational state transfer. Rest was first defined by a gentleman named Roy Fielding. Roy made use of REST to design URI or Uniform Resource Identifiers, and HTTP 1.1. Many applications and websites now offer Web Services, and it is becoming increasingly common to use REST for this rather than the overly complicated SOAP.

REST has 6 main constraints:

Client Server

Stateless

Cacheable

Layered System

Code On Demand

Uniform Interface

In addition REST makes use of specific HTTP Verbs or request methods, such as GET POST PUT and DELETE

This table gives a great overview and use cases of the various RESTful request methods. You might also like to see how to build a rest api with node and express.

RESTful API HTTP methods

Resource GET PUT POST DELETE Collection URI, such as /resources List the URIs and perhaps other details of the collection’s members. Replace the entire collection with another collection. Create a new entry in the collection. The new entry’s URI is assigned automatically and is usually returned by the operation. Delete the entire collection. Element URI, such as /resources/item17 Retrieve a representation of the addressed member of the collection, expressed in an appropriate Internet media type. Replace the addressed member of the collection, or if it doesn’t exist, create it. Not generally used. Treat the addressed member as a collection in its own right and create a new entry in it. Delete the addressed member of the collection.

How Does REST Tie Into Laravel?

Taylor Otwell and his team took into consideration the architectural goals of the RESTful style of development. We have access to this by using a resource in our routes.php file. First up though, let’s run this command:

php artisan routes

+--------+-------------------+------+------------------------+----------------+---------------+ | Domain | URI | Name | Action | Before Filters | After Filters | +--------+-------------------+------+------------------------+----------------+---------------+ | | GET agents | | AgentsController@index | | | | | GET agents/{name} | | AgentsController@show | | | +--------+-------------------+------+------------------------+----------------+---------------+

These routes are still registered to our application when we created a couple of explicitly routed controllers in the Introduction to Laravel Controllers post. This is pretty cool that we can run a simple command and look at all registered routes in the application, don’t you think?!

Now open up your routes.php file, clear all routes out of it, save the file, then run the command again:

php artisan routes

Artisan will gleefully tell us

Your application doesn’t have any routes.

Excellent! Now we know how to check on the status of our registered routes at any time.

Route Resource

Warning: Mind blowing activities beyond this point.

Let’s create a route resource in our routes.php file. It’s really easy, we just add a snippet like this:

1 Route:: resource ( 'blogposts' , 'BlogpostsController' ) ;

What this tells us is that we are creating a blogposts resource and our BlogpostsController will handle actions taken on this resource. That one line of code just did a lot for us. Ok so what’s the big deal Jack? Well, why don’t we run the command again and see what happens:

php artisan routes

+--------+--------------------------------+-------------------+-----------------------------+----------------+---------------+ | Domain | URI | Name | Action | BeforeFilters | After Filters | +--------+--------------------------------+-------------------+-----------------------------+----------------+---------------+ | | GET blogposts | blogposts.index | BlogpostsController@index | | | | | GET blogposts/create | blogposts.create | BlogpostsController@create | | | | | POST blogposts | blogposts.store | BlogpostsController@store | | | | | GET blogposts/{blogposts} | blogposts.show | BlogpostsController@show | | | | | GET blogposts/{blogposts}/edit | blogposts.edit | BlogpostsController@edit | | | | | PUT blogposts/{blogposts} | blogposts.update | BlogpostsController@update | | | | | PATCH blogposts/{blogposts} | | BlogpostsController@update | | | | | DELETE blogposts/{blogposts} | blogposts.destroy | BlogpostsController@destroy | | | +--------+--------------------------------+-------------------+-----------------------------+----------------+---------------+

Whoa. What just happened? Well, Laravel just registered 8 RESTful routes for you in the blink of an eye.

Ok so now we need to start thinking about resources. In this case above, blogposts is our resource. So what does this mean? Let’s go through line by line:

GET blogposts

Sending a GET request to the http://you.rock/blogposts URI will list all blog posts.

Controller Method: index()

GET blogposts/create

Sending a GET request to the http://you.rock/blogposts/create URI should give us a form to create a new blog post.

Controller Method: create()

POST blogposts

Once you enter all of the information into your form, it should send a POST request to http://you.rock/blogposts which will store it in the database.

Controller Method: store()

GET blogposts/{blogposts}

Sending a GET request to http://you.rock/blogposts/blogpostid or http://you.rock/blogposts/slug-of-blogpost should enable viewing of a specific blogpost.

Controller Method: show()

GET blogposts/{blogposts}/edit

Sending a GET request to http://you.rock/blogposts/blogpostid/edit or http://you.rock/blogposts/slug-of-blogpost/edit should provide a populated form to edit an existing blogpost.

Controller Method: edit()

PUT blogposts/{blogposts}

Sending a PUT request to http://you.rock/blogposts/blogpostid or http://you.rock/blogposts/slug-of-blogpost should update a specific blogpost.

Controller Method: update()

PATCH blogposts/{blogposts}

PATCH is similar to PUT .

DELETE blogposts/{blogposts}

Sending a DELETE request to http://you.rock/blogposts/blogpostid or http://you.rock/blogposts/slug-of-blogpost should destroy or delete a specific blogpost.

Controller Method: destroy()

Wow. That’s some heavy duty stuff 🙂

Create Your Controller

Now that we have created our resource, and examined all of the registered routes that it provides to us, let’s create a controller to leverage what we have done so far:

php artisan controller:make BlogpostsController

Result: Controller created successfully!

Let’s remember our Blogpost Model, which makes use of the belongsToMany relationship. The code is here to refresh our memory:

1 2 3 4 5 6 7 8 9 10 <?php class Blogpost extends Eloquent { protected $guarded = array ( ) ; public function tags ( ) { return $this -> belongsToMany ( 'Tag' ) ; } }

Awesome! Since we have a model already made, let’s add some code to the index() method of our Blogposts Controller so we can test our new resourceful routing.

1 2 3 4 5 6 7 8 9 10 11 12 13 <?php class BlogpostsController extends BaseController { /** * Display a listing of the resource. * * @return Response */ public function index ( ) { return Blogpost:: all ( ) ; }

Ok let’s visit http://you.rock/blogposts . Fingers Crossed.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 [ { "id" : 1 , "title" : "You Should Use Twitter Bootstrap!" , "body" : "If you are a design savvy person, you may have noticed that Vegibit uses the Twitter Bootstrap Framework. I freaking love this framework, and you should too, or rather if you’re unfamiliar, you will love it by the time you finish reading this article." , "created_at" : "0000-00-00 00:00:00" , "updated_at" : "0000-00-00 00:00:00" , "slug" : "you-should-use-twitter-bootstrap" } , { "id" : 2 , "title" : "Twitter Bootstrap Modal Tutorial" , "body" : "Modals are a fun way to add interactivity to your website. When a user needs to make a choice, or confirm an action, the classic jquery modal popup makes perfect sense." , "created_at" : "0000-00-00 00:00:00" , "updated_at" : "0000-00-00 00:00:00" , "slug" : "twitter-bootstrap-modal-tutorial" } , { "id" : 3 , "title" : "Laravel Eloquent ORM Tutorial" , "body" : "Eloquent is the very powerful and expressive ORM or Object Relational Mapper in Laravel. If you know how to work with Objects in PHP, then you know how to use Eloquent! " , "created_at" : "0000-00-00 00:00:00" , "updated_at" : "0000-00-00 00:00:00" , "slug" : "laravel-eloquent-orm-tutorial" } , { "id" : 4 , "title" : "Install Laravel on Windows" , "body" : "This is going to assume we are starting from scratch using a fresh install of WAMP 2.4 on Windows." , "created_at" : "0000-00-00 00:00:00" , "updated_at" : "0000-00-00 00:00:00" , "slug" : "install-laravel-on-windows" } , { "id" : 5 , "title" : "Install and Configure Windows Server 2012 with Windows Powershell" , "body" : "Windows PowerShell is an amazingly powerful tool to help you with common windows administrative tasks. If you are comfortable with one of the myriad of scripting languages available today, Powershell will be easy for you to learn while also providing the benefits of command line administration. " , "created_at" : "0000-00-00 00:00:00" , "updated_at" : "0000-00-00 00:00:00" , "slug" : "install-and-configure-windows-server-2012-with-windows-powershell" } ]

Oh Yeah Baby! Hey now, Hey now, here what I say now! So how does it work? Well here is how the code would flow:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 // our routes are set up with one line in routes.php Route:: resource ( 'blogposts' , 'BlogpostsController' ) ; // our BlogpostsController has an index method public function index ( ) { return Blogpost:: all ( ) ; } // our Blogpost model extends eloquent // so we can use return Blogpost::all(); // in our controller above class Blogpost extends Eloquent { protected $guarded = array ( ) ; public function tags ( ) { return $this -> belongsToMany ( 'Tag' ) ; } }

This is just an example of our index() method running. Moving forward, we’ll want to create the logic in our Blogposts Controller to make our create() store() show() edit() update() and destroy() methods functional as well.

The RESTful Takeaway

Using Resourceful Routing and the RESTful development style has many advantages for you.

Convention Over Configuration

It helps keep you in the mindset of convention over configuration. This way, instead of naming your controller methods all kinds of crazy things, you’ll know that as long as you use index() create() store() show() edit() update() and destroy() , then things will typicaly just work. A good point to remember as well is that, if you use Artisan to create your controllers, those methods will be in there by default anyway.

Much Cleaner Routes File

You’re not going to escape your routes.php file, you’ll need it for everything you do in Laravel. So it would make sense to keep it as clean as possible. We can start with routing to closures, clean things up with explicit routing to controllers, or just register a resource and let Laravel auto configure our registered routes, 8 at a time for us. Even if we are using explicit routing to controllers, if your application starts to get fairly big, having tens or even hundreds of route definitions for every single action you need to take is going to get cumbersome.

Get Explicit Only When Needed

We can see now that Resourceful Routing is really good for us. That doesn’t mean it is going to fit every single facet of your web development needs. No big deal. Just register resources to get all of the common and repetitive tasks you are going to need to do anyways taken care of, then when you have edge cases that don’t fit into this convention, simply register some explicit routes to controllers to complete whatever it is you are trying to do.