Laravel: Is It Really Clean and Classy?

Tweet

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

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://www.mosheteutsch.com Moshe Teutsch

    Nice article.

    Why does Laravel use so many static classes? In general this is considered bad practice, as it is harder to test and throws away the possibility of polymorphism.

    • http://mercenarydesign.com.au Robbo

      They use static calls because it is so clean and easy to read. But they also have ways to counter the down sides of it. They have a dependency injector for test cases and also you can overwrite anything as the class names are aliases of the core classes, you simply have to tell it to use your own class.
      I believe Laravel 4 makes this even better and it is by far the best framework I have ever used! I want to drop all my actual work to work with it instead.

  • Anahkiasen

    Some shortcuts can be made here.
    Schema::table(‘table’, function($table) { $table->create(); })
    can be replaced by
    Schema::create(‘table’, function($table) {})

    Todo::where_id($id)->first();
    can be replaced by
    Todo::find($id);

    Just thought I’d point it out :)
    Good article, nice to see more and more people talking about Laravel !

  • Vincent

    No framework that uses so much Singletons and static methods is clean and classy. This is just a cover up for plain procedural programming… this framework is ridiculous and EXTREMELY amateur compared to what we we have: much better architectures available such as Zend Framework 2 and Symfony 2.

    • Robbo

      You obviously don’t know much about the framework as your comment is simply wrong.

    • Alchemication

      Unfortunately for Laravel I have to agree to that comment. Had worked with lot of frameworks and even old-school CodeIgniter looks better in terms of ABusing static methods.

    • James Wagoner

      What you think are static methods are actually facades. If you take a look at the actually core library, you will see how it actually works.

      Don’t be so quick to shoot down a great framework because you didn’t take the time to investigate and learn. You barely need to look at the docs as the core files are so well documented already.

  • christian

    *cough *cough.. RoR clone..

    You know, I can deal with the copy/flattery cliche, but when that is coupled with such enthusiastic self-praise, I honestly want to puke all over myself. Seriously, naming what essentially strives to be a direct port of ActiveRecord::Base as “Eloquent” is freaking hilarious/terrifying

  • Jesper

    @Vincent , silly comment! Make some real arguments and don’t compare frameworks suited for different purposes – that makes no sense imho. Symfony 2 is great, but not when trying out a idéa which you want to deploy fast. Creating a simple blog in Symfony 2 is waste of time in my opinion and is not what Symfony 2 was created for, here however Laravel comes in really handy. And you can’t argue and say that Laravel is not clean and classy, the code is really readable and clean. Even a three year old would now what’s happening. Btw, I’m a Symfony2 fanboy too, but Laravel is really great too (plus it uses the HTTPFoundation from Symfony!)

    • George

      Creating a simple blog is a waste of time, just use WordPress…

      Laravel is still a young framework, promising, but it uses a lot of patterns & best practices incorrectly.

      Singletons / static methods are generally a bad practice where objects only live in a request, because it’s impossible to unit test it, but I think it has it’s place in the dev. world even though if it wasn’t meant to be used in PHP where there’s no shared memory state.

      I can’t speak on behalf of the framework’s author, but I read that he’s coming from .NET and he used a lot of practices from .NET so Laravel to be a RoR clone is plain wrong.

      • Christian

        I don’t care where he came from.. have you ever used rails/migrations/activerecord? If so, you’d um, like, notice that not only does it follow rails practices, but the method signatures are EXACTLY THE SAME in many cases.
        has_and_belongs_to_many :huh..

        • http://alex-glover.com Alex Glover

          @christian, the method names are the same because that is the name of the relationship type, so why try to be creative to come up with another name? It is a HABTM relationship…

  • Tjorriemorrie

    @Jesper, I agree and support @Vincent’s comment.

  • l

    Laravel’s documentation is far away from CodeIgniter.

  • blacksonic

    forget about this framework if you develop in TDD
    statics and singletons are a nightmare during tests

  • Jeff

    Codeigniter is much simple with a natural flow of coding. CI documentation is more exaustive than other framework.

  • http://www.blueweb.sk Jakub Jarabica

    Those static classes are pain :/. You should check out Nette Framework: http://doc.nette.org/en/ and give it a shot.

    • Christian

      jesus christ.. another php framework

  • Eric Barnes

    For all you guys talking about static classes here is a post that goes over the reason for this in more detail. – http://forums.laravel.com/viewtopic.php?pid=3237#p3237

  • Michael

    Before commenting about the static classes, you should look at the source code. Most of them aren’t static, they are just passed through magic methods. Laravel is 100% unit tested.

  • http://awellis.me Andrew Ellis

    I have used CodeIgniter, Zend Framework, Yii, Kohana, Fuel, and Laravel.

    Laravel is the only framework I have truly enjoyed using, and I REALLY liked Kohana. It took a lot for me to move away from Kohana.

    Most of you who jumped into instantly bashing this framework without taking a complete look through the code to see how the core actually works have no reason to bash it. Do not judge a book by it’s cover as they say.

    If build one small pet project with this framework, I can guarantee that your opinions of this framework will change.

  • http://www.itoctopus.com Fadi El-Eter

    Will form validation work automatically in Laravel? How could you instruct it that something is required, or that a field has to be of type integer/email/etc…?

    • Marcus

      You can establish the rules in your model.
      e.g.
      public static $rules = array(
      ‘name’=>’required|min:2′
      );

  • http://www.andrewperkins.net Andrew

    If you’re interested in learning more about Laravel in a little more detail I have about 10 video tutorials covering the basics on Youtube: http://www.youtube.com/playlist?list=PL09BB956FCFB5C5FD

    • Henrik

      Thank you, the first video gave me great insight. If I stick around I may watch the other ones as well.

  • Chris

    By the way I’m totally missing any file names or simple where-to-copy-this thing. I know, this is probably not was this tutorial/showcase was written for, but i think EVERYBODY here wants to try this code by themself.
    After struggling around with your code and laravel for 3hrs i’m still stuck and still dont know how to create this simple todo app. It’s a pity. And a killer argument against Laravel.

  • Nique

    I think the Framework is just fine. But what the author of the framwork says on his frontpage is not entirely true. The docs aren’t that great as it is explained for example you have to ‘register’ a bundle.. but it is never told where you have to do that.. in what file?! I hate such docs.. its half work.

    • http://mikael.siirila.net/ Mikael

      Um, bundles.php.

  • Rhodri

    A pedantic point but…
    “The controller is where all the business logic is located”
    Really?

    • Asgaroth

      I know. I was like “WTF” when I read that.

  • Joao

    The documentation is really bad. And worst part is reading the forum and checking for sample/share code and seeing people posting to some paid online tutorials lol

    • http://maxoffsky.com Maks

      Joao, how is the documentation so bad? Also which tutorials are “paid”?

    • http://laravelish.wordpress.com/ Alex

      Check the API docs, check the source code!

  • chakkimatti

    Joao is apparently referring to the Laravel Essentials direct, which is a Nettuts Premium. Seems to me, that a lot of these negative comments focus on one word they didn’t understand or one paid tutorials WTF. How many paid tutorials are there for Rails, I wonder? At least, I’m enjoying the Laravel community and developing/learning it.

  • Asif

    Well all those who are against Laravel, do some search and give laravel a try. Laravel 4.0 if u can atleast :)

  • http://phpixie.com PHPixie

    Using so many static classes breaks the most important part of OOP: understanding how the system actually works.
    In Kohana for example you do:
    $this->request->param(‘id’) to get a parameter.
    this way you actually see where the request object is and what it does.
    The templating system (Blade) is plain stupid, it’s much better to use plain PHP code for templating because:
    1) syntax highlighting
    2) easier debugging
    3) you can actually do some logic (e.g. coloring even and odd rows in the table) much simply
    If you want to try out a new framework, try PHPixie. It is much more logical to use at performs better than Laravel

    • Alexander Cogneau

      Hi, I do not completely agree on your comments. For example with Laravel, and especially its new version 4, you are not bound to using Blade you can use any other of your own systems if you want. Then with the request object, why would you do that? I mean, okay you see that the parameter is in the request object, but you can also easily access parameters using them as arguments in your controller method.

    • lossendae

      This post can enlight you on the use og static in Laravel and many modern framework: http://philsturgeon.co.uk/blog/2012/12/why-do-some-php-devs-love-static
      Blade (or Twig) for that matter are actually really nice and better from a designer standpoint as php tends to be verbose. Again, modern IDE does play really good with Smarty or Twig allowing syntax highlighting and debbugging as well.
      I guess you just don’t really know what you’re talking about here… or you’re just fed up with all the Laravel hype :)

  • http://phpixie.com PHPixie

    HAving a request object allows you to use the HMVC pattern, e.g. to send requests between your own controllers, which is very useful in larger systems. A controller cna then construct a request execute it with another controller and process the response.

    • Alexander Cogneau

      I see, that is indeed a nice addition, and luckily for us it is included in Laravel version 4. Laravel 4 uses the Symfony Request component which makes things like this possible. You might want to take a look at my article that has just been published about Laravel 4: http://phpmaster.com/whats-new-in-laravel-4/

      It doesn’t cover the request object but it still might contain some cool information for you :)

      While I see that you are quite attached to the PHPixie framework, it might still be useful to check other frameworks and to check their advantages/disadvantages over using your own framework.

      • http://phpixie.com PHPixie

        Well I did use most of the mainstream frameworks, even a few exotic ones. PHixie has a bit different focus then Laravel even. It just provides you with a fast lightweight base, rather then tries to do everything. If I has to chooses between the mainstream ones, I’d go with Koahana probably

  • sanny

    i got an error that Class ‘Todo’ not found … i don’t what’s wrong with