cult3

Setting up your first Laravel 4 Controller

Jul 01, 2013

Table of contents:

  1. What is a Controller?
  2. What do I create Controllers for?
  3. RESTful Controllers
  4. Creating a Controller in Laravel 4
  5. The anatomy of a Controller
  6. Conclusion

So far in this series we have focused all of our attention on Models. Models form a critical component of the MVC architecture and so it’s usually a good idea to start building from your Models upwards.

In this next section of the series I’m going to start looking at Controllers. Controllers are what direct the traffic in your application. I often hear a lot of confusion about what should go in to a Controller and what should not. Similarly with Models, it’s important to have the correct separation of concerns from the outset as it will make your life a lot easier going forward.

In this post I’m going to be going over exactly what a Controller is, how it should be used, what should go into it and then finally how to create your first Laravel 4 Controller.

What is a Controller?

So what exactly is a Controller? In a MVC architecture (What is MVC?), Models are concerned with the business logic of the application, Views are concerned with displaying information to the User and so Controllers are only concerned with directing traffic between Views and Models.

Fat Model, skinny Controller is a common phrase that is used to describe MVC architecture. Whilst it’s arguable whether Models should be fat, your Controllers should definitely be skinny.

Skinny Controller basically means, you don’t really want any logic in your Controller that is likely to be repeated elsewhere in your application. For example, it’s still quite common to see validation in an application’s Controller. This validation is likely to be repeated (Don’t Repeat Yourself) and so it should be abstracted away.

Controllers should only really be used for passing messages between the Model and the View.

What do I create Controllers for?

Another common point of confusion that I often hear is, What do I make Controllers for?. This can seem a little bit confusing at first, but actually it is really straight forward.

You should have a Controller for every resource of your application.

So for example, in Cribbb we have a resource called Users. I want to create certain actions on that resource like displaying all users, displaying a specific user, updating a user’s details or deleting a user all together.

This is a general simplification of what to use Controllers for. Of course there will always be edge cases, but for the most part, just remember that every resource of your application will also likely need a Controller.

RESTful Controllers

Another common phrase you might of heard is RESTful Controllers. REST (What are RESTful Web Services?) is simply a set of rules that govern how data transfer should happen in web applications.

If this sounds a little bit scary, don’t worry, REST actually makes dealing with this stuff a whole lot easier! REST defines certain methods that are applicable for almost every type of resource in a web application. REST is also a fundamental part of how the Internet works and so it makes creating web applications much easier.

For example, for our Users resource, there are certain actions that we will require.

  • Create new Users
  • Retrieve a list of all Users
  • Update the details of a User
  • Delete a User all together

Create, Retrieve, Update and Delete are basically all you need to know about REST. These four actions are the basis for how REST works. Each of those actions map to a RESTful method. So creating a RESTful application is a simple as following the rules that are already in place for you.

Believe me, having a predetermined set of rules will make your life a lot easier!

To read more about REST, have a look at What are RESTful web services?.

Creating a Controller in Laravel 4

So now that you have an understanding of what Controllers are, how they fit into MVC applications and what exactly is REST, we are ready to start creating our first Controller.

The first Controller I’m going to create is for the User resource.

As with a lot of actions in Laravel 4, we can automatically generate the boiler plate code for the Controller by simply running an Artisan command:

$ php artisan controller:make UsersController

Here I’m simply instructing Artisan to make a controller called UsersController.

This should create a new file under app/controllers called UsersController.php.

Your Controller should look like this:

class UsersController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store()
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     * @return Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     * @return Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param int $id
     * @return Response
     */
    public function update($id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return Response
     */
    public function destroy($id)
    {
        //
    }
}

The anatomy of a Controller

So as you can see from the code generated above, Laravel will automatically create a RESTful Controller for you. This is brilliant because you already have a template for the actions that you are going to need.

I’ll now go through each of the methods and describe exactly what they should be used for.

Index

The Index method is commonly used for displaying a listing of the resource. It is retrieving this list from the database and so it uses the GET RESTful method.

So for example, the URL /user would display all users in the application.

Create

The Create method is used to display a form for creating a new user. Again this is a GET method because we are retrieving the form.

For example, the URL /user/create should display the form that allows a user to sign up.

Store

The Store method is how the application actually inserts the new User into the database. After the form is submitted on /user/create it is POSTed to the Store method which takes the data and inserts it into the database.

When you are creating a new resource, you should be using the POST RESTful method.

Show

The Show method is used to display the details of a particular record of the resource. Again this method uses the GET RESTful method because it is simply retrieving from the database.

For example, to see the profile page of the user with an id of 1, you would go to the URL /user/1 in your browser.

Edit

The Edit method is for (not surprisingly) editing a record. This method also uses the GET RESTful method in the same way as the Create method because it should be used to display a form for the user to make changes.

For example, to edit the profile of user 1, you would go to /user/1/edit.

Update

The Update method is for updating the database once the form on the edit page has been submitted. The Update method uses the RESTful method of PUT. By default, PUT is not actually commonly used to update a resource in many web applications because it is not made available like GET and POST are. However, you don’t need to worry about this because Laravel is able to handle it for you.

To update a record of the user with an id of 1, you send a PUT request to /user/1.

Destroy

And finally, to delete a user, you would use the destroy method. This method uses the DELETE RESTful method.

To delete user 1 from the application, you would send a DELETE request to /user/1

Conclusion

Controllers don’t need to be as complicated as they are made out to be. There is a lot of confusion out there which makes the problem a lot worse.

All you need to remember is, your Controllers should be very simple. If you ever get to the stage where you feel like your Controller is doing too much, it probably already is.

If you find yourself repeating logic in Controllers, try and abstract it away so you have one point of reference for that bit of logic.

RESTful can seem a bit daunting when you first hear about it, but really, it is there to help you build better applications. When you follow the rules of REST, you will have to make fewer decisions about the architecture of your application, it will work a whole lot better and it will be much easier for other people to intuitively pick up.

Next week I’m going to start looking at building out the User Controller of Cribbb.

This is a series of posts on building an entire Open Source application called Cribbb. All of the tutorials will be free to web, and all of the code is available on GitHub.

Philip Brown

@philipbrown

© Yellow Flag Ltd 2024.