|

Laravel RESTful Controllers

Laravel RESTful

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:

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:

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:

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.

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

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:

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.