PHP - - By Alexander Cogneau

Laravel: Is It Really Clean and Classy?

Laravel is a clean and classy framework for PHP web development. Freeing you from spaghetti code, Laravel helps you create wonderful applications using simple, expressive syntax. Development should be a creative experience that you enjoy, not something that is painful. Enjoy the fresh air.

That’s the text which can be found on the Laravel homepage and, if we’d believe it, wouldn’t it be wonderful? Let’s test this claim by building a simple TODO application and see how much effort we have to put into it.

Migrations

First we’ll design the database. The application requires a rather simple schema, a single table with 5 columns to store an ID, title, description, and timestamps when the task was created and last updated.

Laravel has a feature called migrations, which you might be familiar with already if you’ve used other frameworks like Ruby on Rails. Migrations are files which are used to update your database. As they are executed, they change your database schema in such a manner that you can easily apply updates to it.

For our application, the migration looks something like this:

<?php
class Create_Todo_Table
{
    public function up() {
        Schema::table("todos", function($table) {
            $table->create();
            $table->increments("id");
            $table->string("title", 20);
            $table->text("description");
            $table->timestamps();
        });
    }

    public function down() {
        Schema::drop("todos");
    }
}

The up() method is called when the migration is being executed and the down() method is called when the migration is being reverted.

The Model

As Laravel is an MVC framework, we’ll need to create the model. Like with any other MVC framework you might know, the model is the component which is responsible for communicating with the database. Our table is simple, and so it only needs a simple model:

<?php
class Todo extends Eloquent
{
    public static $timestamps = true;
}

The class name is “Todo” and Laravel will automatically associate this with the todos table in our database. Eloquent is an ORM class for models that Laravel uses, which provides a smooth way to work with database objects.

The $timestamps property is set to true, which means that whenever a new entry is created or an existing entry is updated, the created_at and the updated_at fields will be updated accordingly.

The Controller

Now let’s create the controller. The controller is where all the business logic is located, and should therefore contain functionality to:

  • Retrieve all of the entries in the table to list them
  • Retrieve the information of a specific entry with a given id
  • Delete an entry with a given id
  • Compose a form to add a new entry
  • Add the new entry to the database and compose a message to confirm the addition

This gives us the following controller class with five methods, which we call actions. An action’s declaration must be preceded by the prefix “action_”.

<?php
class Todo_Controller extends Base_Controller
{
    public function action_list() {
        $todos = Todo::all();
        return View::make("list")
                ->with("todos", $todos);
    }

    public function action_view($id) {
        $todo = Todo::where_id($id)->first();
        return View::make("view")
                ->with("todo", $todo);
    }

    public function action_delete($id) {
        $todo = Todo::where_id($id)->first();
        $todo->delete();
        return View::make("deleted");
    }

    public function action_new() {
        return View::make("add");
    }

    public function action_add() {
        $todo = new Todo();
        $todo->title = Input::get("title");
        $todo->description = Input::get("description");
        $todo->save();
        return View::make("success");
    }
}

The code is very straightforward. The first method action_list() will get all of the entries in the database. This is where Eloquent makes things easy, requiring only Todo::all() to fetch them. Then it returns a view with all of the entries from the database bound to the $todos variable.

The other methods are also easy to read. They mostly exist to manipulate a database object and return a view with some data bound to it. The last method might be an exception; the action_add() will be called when submitting the form to add a new TODO entry. Input::get() is used to retrieve the submitted form values.

The View

Now we’ve come to the view. Laravel uses its own Blade templating engine which gives us clean and readable code. I will give an example of the first view, the list. With the make/with statement under the return of the view from action_list(), we put all the results of Todo::all() into $todos. We can now use that in the view:

<h2>Todo list</h2>
<p>{{ HTML::link_to_action("todo@new", "Add new todo") }}</p>
<ul>
@foreach($todos as $todo)
    <li>{{ HTML::link_to_action("todo@view", $todo->title, array($todo->id)) }} - {{ HTML::link_to_action("todo@delete", "Delete", array($todo->id)) }}</li>
@endforeach
</ul>

That’s all it takes! First we let Blade create a link to the controller’s action action_new(). Then we see the foreach statement which is quite similar to the one native to PHP. For every task we create a link to view the entry. The link text is the second parameter, $todo->title, and any parameters for the action should be provided next. We need the ID of the entry we want to view, which $todo->id provides. We also create a link to delete the task, again including the ID of the TODO as parameter.

Conclusion

So, that was that, and indeed it is simple to make an application using Laravel. The code is straightforward and easily readable. I hope this was useful to you, and you consider using Laravel with your next PHP application. See you next time!

Image via Fotolia

Sponsors