What’s New in Laravel 4

Laravel is a PHP framework which uses the MVC pattern. Of course, there are many such projects and I’m not going to compare Laravel with other frameworks in this article. Instead, I’m going to share with you what’s new in the newest version of Laravel – Laravel 4.

Decoupled Components

Laravel 4 does not contain very much code as you can see on its GitHub page. In fact, the app project just registers services it uses. This is the biggest change in Laravel 4; instead of having all of the code packed in one repository, the functionality is separated in so called Illuminate Components. The app project just uses Composer to manage the dependencies that we are familiar with from the retro Laravel: the Controller/Routing system, the Object Relational Mapper named Eloquent, and view management with the Blade templating engine. They are now all organized as separated components and are decoupled using service locators.

Maybe you’re not impressed, and it’s possible that you’re asking yourself: “Wow, is that it? What’s the big deal?” The big deal is that, with true decoupling, we can pick out the Illuminate Components we need and use them in our own project. So, you’re just looking for a nice ORM, but you don’t want the routing system, the views, the pagination and the mail component? No problem, you can use what you want. You just take what you need and not the whole ‘robust’ framework.

Creating a “Normal” Project

For the users who want to use the complete framework as always, just retrieve this repository: github.com/illuminate/app.git. After that, install Composer and go to the directory where the code is and run composer update. This will get you all of the Laravel dependencies. Inside the app directory, everything is similar to the old Laravel – the directory structure and the files – so it won’t take much effort to update your Laravel 3 projects to Laravel 4.

Routes

Just like before, routes are defined in the routes.php file. You can return anything you want, although note that, for controllers, Laravel doesn’t use magic renaming anymore. In Laravel 3 you could call a controller method like this:

<?php
Route::get('/', 'home@index');

The controller went by the name of HomeController. But now you have to use:

<?php
Route::get('/', 'HomeController@index');

While this might not seem like a feature enhancement, it really is. For example, if you use the route component as stand-alone library, you aren’t bound to Laravel’s naming conventions.

Better Code through Testing

Critics of previous versions of Laravel argued its code would never be able to achieve high quality status. By using a lot of static methods for to produce nice and clean code, the developers had to sacrifice the project’s testability. The main developer (Taylor Otwell) did a great job balancing easy code and testability, but it’s true the code could never be fully tested.

That era ends now. By using an IoC container for registering all of the components, everything can be fully tested. Each component has tests for most of its features, and with each commit those tests are validated by Travis CI. To preserve a clean way of calling components, Laravel uses the façade pattern.

The Container and Its Bindings

When you create a Laravel project, you use an IoC container to resolve all of the dependencies. The Application class is extended from IlluminateContainer. While you use facades to call component methods, you can still bind things to the container to make them available throughout your whole application. For example:

<?php
App::bind('hello', function()
{
    return "Hello to you, sir";
});

Route::get('/', function()
{
    return App::make('hello');
});

Here we’ve bound a function that returned the string “Hello to you, sir” to ‘hello’ in the container.

The container also allows us to lazily bind objects without looking at its constructor arguments. This can be done through Reflection. For example:

<?php
Class writer
{
    public function write()
    {
        return 'A good day to you, sir';
    }
}

Class helloWorld
{
    protected $writer;

    public function __construct (Writer $writer)
    {
        $this->writer = $writer;
    }

    public function write()
    {
        return $this->writer->write();
    }
}

Route::get('/', function()
{
        return App::make('helloWorld')->write();
});

You can see that Laravel automatically resolves our dependencies by creating a new Writer class and uses it as argument in the helloWorld class constructor. If you want a specific writer instance used as the argument, you can also bind that object to the container using the approach shown in the previous example.

Improved CLI

Laravel’s famous CLI, known By the name Artisan, has received some major improvements as well. Using the command line component from Symfony, Artisan now exhibits more friendly behavior. For example, you can get all the available commands just by executing artisan list, and you can get extra information on the commands and what it does.

New Database Features

For the database component, which most Laravel users will use in their projects, the most notable update is database seeding. If you go to your app/database directory, you’ll see a directory named seeds there.

To show you this feature, we’ll first need to have a test database table to work on. So, set your connection details in app/config/database.php, navigate to the root directory (above app) and execute php artisan migrate:install to install the migration tables. Then, run php artisan migrate:make create_comments_table --create="comments" which creates a test table named comments.

Look in the app/database/migrations directory and you’ll see your migration there. We can use the schema builder so that we don’t have to use raw SQL queries. In the up() method, fill this in:

<?php
public function up()
{
    Schema::create('comments', function($table)
    {
        $table->increments('id');
        $table->string('title');
        $table->text('body');
        $table->integer('author');
    });
}

And in the down() method, put:

<?php
Public function down()
{
    Schema::drop('comments');
}

Save your file and run php artisan migrate and you should receive a confirmation message that it succeeded.

Now let’s make the seed. A seed is some sort of test data you want to insert in your database for testing your application. Create a new file named comments.php in the database/seeds directory with the following content:

<?php
return [
    [
        'title' => 'hello there',
        'body'  => 'I wish you a warm welcome',
        'author' => '5'
    ],
    [
        'title' => 'Another hello',
        'body' => 'I want to greet you another time',
        'author' => '1'
    ]
];

The code presents a multidimensional array where every member array is a record. Now execute php artisan db:seed. Now your database is seeded (contains the test data)! You can do this every time you do a migration.

Using Stand-Alone Components

The biggest update to the new framework, as I said earlier, is the availability of separate components. Laravel uses an instance of IlluminateFoundationApplication as an IoC container so we don’t have to worry about the dependencies, and we have the ability to use our own custom components. That last can be edited in app.php in your config directory.

In the future I’m sure there will be many projects available for wrapping Laravel components and to use them in your project. One example is Capsule, which provides us some methods for accessing the components. Right now only the database component is supported, but this will change in the future. For example, a database connection can be established by following code:

<?php
CapsuleDatabaseConnection::make('main', [
    //database credentials
], true);

Now you can execute fluent queries by using the static methods of the CapsuleDB class. For documentation, look up at the project on GitHub.

Good Job!

I think the Laravel developers did a great job again contributing some major improvements to the framework. Testability isn’t a problem any more, and neither is decoupling. Laravel 4 very well may be one of the greatest (if not THE greatest) PHP frameworks currently available thanks to the hard work of all the developers.

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://sabaki.aisites.com/imd311/imd311simmonds.html maxw3st

    Wow! This looks really good. I’ve not heard of Laravel before this article. First impression is that it looks like PHP is being used to develop a very ActionScript–like language framework. To me that’s pretty exciting and I need to get to work learning it.

  • Juukie14

    Great article. I’m using Laravel 3 for a while now and I really makes me enjoying programming. Can’t wait for Laravel 4.

    • Alexander Cogneau

      I’m glad that you are as enthusiastic as I am

  • http://www.maltblue.com Matthew Setter

    Alexander, these look like some steps in the right direction, specifically regarding testability. Good post.

    Matt

    • Alexander Cogneau

      Thank you!

  • Alexander Cogneau

    For those interested: the first Laravel 4 beta will be released this week with full documentation!

  • keripix

    Im actually planning to use laravel for my project. Knowing that laravel 4 will be beta this week, should I use the 4th version or still use the stable 3rd version?

    And if I choose to use Laravel 3, will the migration to the 4th version be easy?

    • Alexander Cogneau

      Many have asked that, I would suggest, if you want to have your app online soon, I would use Laravel 3, the API will be mostly the same, and much documentation on upgrading will be available.
      If you have enough time, I would use Laravel 4

  • peter

    Does the Eloquent ORM support optimistic locking? I can not find such a feature it in Laravel documentation.

    • Alexander Cogneau

      I’m afraid that it doesn’t.

  • https://www.facebook.com/groups/LaravelCommunity/ Asif

    Nice post! I’m a fanboy of Laravel PHP Framework! and waiting for L4! going to share this post on Laravel Community group on Facebook!

  • Gazzery

    Is Laravel 4 HMVC?

    • Alexander Cogneau

      It can call other controller’s actions if that is what you mean.

  • Marco

    I’ve been using the Symfony 2 framework for my latest project. Before this project I mainly worked on e-commerce sites based on Magento. I’m really enjoying coding on the Symfony 2 platform. Everything seems to work in a logical way and the documentation is great. How does Laravel 4 compare to Symfony 2? Am I missing out :) ?

    • Alexander Cogneau

      Hi Marco, they have some similarities, in fact Laravel 4 uses the Symfony2 Http Component so that is the same. I don’t have any experience with Symfony so I guess that you should try it out. :)

  • Etaxcrew

    I plan to start my first lesson with laravel. a good idea me start with Laravel 3? or waiting for Laravel 4.

    • Alexander Cogneau

      It won’t make a total difference, most of the API is just the same.

  • http://timothysolomon.co.za Timothy

    FYI: The Github repo link at the beginning of the article is broken..

    • Alexander Cogneau

      Thank you for noticing, since Laravel 4 went into official beta, everything is placed into a new repository.

      I’ve updated the link.

  • Tomica

    Thanks for the interesting review. As a beginner, I must say it’s probably the most useful text about Laravel 4. Makes much more sense to me now.

    Just one thing. In the article, you say: “retrieve this repository: github.com/illuminate/app.git”. When I try to clone that repository, I get the “Repository not found” error. Are you sure the address is vaild?

    • Alexander Cogneau

      Hi, thanks for your comment! :)

      As I also said to Timothy in the comment above, the repository has changed, try cloning https://github.com/laravel/framework.git now.

      • Tomica

        Oh, really sorry, stupid me! I haven’t noticed you’ve made the correction. Thanks a lot for such a quick reply. Maybe it would help to see the link in the text corrected, if that’s possible?

        • Alexander Cogneau

          Hi Tomica, it already is corrected.

  • EDS

    The link to their gitHub page was wrong. It should be https://github.com/laravel