Getting Started with Laravel 4

4 (1 reviews total)
By Raphaël Saunier
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies

About this book

PHP powers many of the largest websites on the planet. Yet, even though it was specifically created for the Web, its shortcomings never cease to frustrate developers. This is where a tool like Laravel comes in. Rather than reinventing the wheel, Laravel reuses tried and tested components and principles and bundles them to form a cohesive whole and makes PHP development enjoyable again.

Getting Started with Laravel 4 is a practical and concise introduction to the Laravel PHP framework. It covers its fundamental concepts and presents the many features that will boost your productivity when developing web applications. After introducing the key concepts and installing Composer, you will build a CRUD application and add more features to it in each successive chapter.

This book introduces you to a different and more enjoyable way of writing PHP applications. You will start by learning about the key principles and the same development practices that Laravel encourages. Then, in subsequent chapters, you will create and successively add more features to a web application.

You will learn how to use the arsenal of tools at your disposal and probably pick up some useful techniques along the way. Indeed, everything you will learn in this book is highly transferrable and applicable to other MVC frameworks. Laravel's routing mechanism, templating language, and object-relational mapper will have no more secrets for you. You will learn how to authenticate users, write tests, and create command line utilities that interact with your application with disconcerting ease. In addition to this, you will probably be surprised by the simplicity and expressiveness of your code.

Publication date:
January 2014


Chapter 1. Meeting Laravel

In the jungle of PHP frameworks, the latest newcomer, Laravel, has been getting more and more attention recently. On many discussion forums, it has even dethroned CodeIgniter and Symfony as the number one recommended framework. What is it about this framework that makes both young and seasoned developers rave about it?

In this chapter, we will cover the following topics:

  • How web application frameworks help to increase productivity

  • The fundamental concepts and the key features of Laravel

  • The general structure and conventions of a Laravel application

  • General advice if this is the first time you are working with a Model-View-Controller (MVC) framework

  • Migration tips for users of the previous version of Laravel

We will look at its key features and how they have made Laravel an indispensable tool for many web developers. We will present the limitations of PHP, especially when it is used without a modern framework, and how Laravel helps you to overcome those shortcomings and write more robust, and more structured, applications. Then, we will take a closer look at the anatomy of a Laravel application and present the different features of PHP as well as the third-party packages it leverages. After reading this chapter, you will have all the conceptual knowledge that is required to get started and build your first application.


The need for frameworks

Of all the server-side programming languages, PHP undoubtedly has the weakest entry barriers. It is almost always installed by default on even the cheapest web hosts, and it is also extremely easy to set up on any desktop operating system. For newcomers who have some experience with HTML, the concepts of variables, inline conditions, and include statements are easy to grasp. PHP also provides many commonly used functions that one might need when developing a website. All of this contributes to what some refer to as the immediacy of PHP. However, this instant gratification comes at a cost. It gives a false sense of productivity to beginners, who almost inevitably end up with unnecessarily complex and tangled code as they add more features to their site. This is mainly because PHP, out of the box, does not do much to encourage the separation of concerns.

The limitations of homemade tools

If you already have a few PHP projects under your belt, but have not used a web application framework before, then you will probably have your personal collection of commonly used functions or classes that you have amassed from one project to the next. These utilities help you solve recurring problems, such as sanitizing database calls, authenticating users, and including pages dynamically. You might also have a predefined directory structure where these classes and the rest of your application code reside. However, all of this will exist in complete isolation; you would be solely responsible for the maintenance, inclusion of new features, and documentation. This can be a tedious and time-consuming task. Not to mention that if you were to collaborate with other developers on the project, they would first have to get acquainted with the way you build applications.

Laravel to the rescue

This is exactly where a web application framework such as Laravel comes to the rescue. Laravel re-uses and assembles existing components to provide you with a cohesive layer upon which to build your web applications in a more structured and pragmatic way. Drawing inspiration from popular frameworks written in both PHP and other programming languages, Laravel offers a robust set of tools and an application architecture that incorporates many of the best features of CodeIgniter, Yii, ASP.NET MVC, Ruby on Rails, and Sinatra.

If you have already used one of those tools or a different framework that implements the Model-View-Controller (MVC) paradigm, you will find it very easy to get started with Laravel 4.


A new approach to developing PHP applications

It is a great time to discover (or fall back in love with) PHP. Over the years, the language has earned itself a bad reputation amongst developers who were forced to work on and maintain badly coded applications. Moreover, at the language level, PHP is also notorious for its naming inconsistencies and questionable design decisions regarding its syntax. As a consequence, there has been an exodus to more credible frameworks written in Ruby and Python. Since these languages were nowhere as feature-rich for the Web as PHP, the creators of Ruby on Rails and Django, for instance, had to recreate some essential building blocks, such as classes, to represent HTTP requests and responses and were, therefore, able to avoid some of the mistakes that PHP had made before them. From the start, these frameworks also forced the developer to adhere to a predefined application architecture.

A more robust HTTP foundation

A few years on , these ideas have found their way back into PHP. The Symfony project has adopted these principles to recreate a more solid, flexible, and testable HTTP foundation for PHP applications. Along with the latest version of Drupal and phpBB, Laravel is one of the many open source projects that use this foundation together with several other components that form the Symfony framework.

Laravel does not just rely on and extend Symfony components, it also depends on a variety of other popular libraries, such as SwiftMailer for more straightforward e-mailing, Carbon for more expressive date and time handling, Doctrine for its inflector and database abstraction tools, and a handful of other tools to handle logging, class loading, and error reporting. In short, rather than trying to do everything itself, Laravel stands on the shoulders of giants.

Embracing PHP

Laravel requires a relatively recent version of PHP, 5.3.7, released in August 2011. This version provides some nifty features that you might not be aware of if you have been working with earlier versions of PHP, or if you're completely new to the language. In this book, and when reading code examples for Laravel applications online, you will encounter some of these new features. For this reason, we will quickly have a look at them to make sure they don't throw you off!

  • Namespaces: It is used extensively in languages such as Java and C# and helps you to avoid name collisions that happen when the same function name is used by two completely different libraries. Namespaces are separated by backslashes, and this is mirrored by the directory structure, with the only difference being the use of slashes on Unix systems in accordance with the PSR-0 conventions. They are declared at the top of the file as <?php namespace Illuminate\Database\Eloquent. To specify the namespaces in which PHP should look for classes, we insert use followed by the "namespaced" class, for example, use Illuminate\Database\Eloquent\Model;.

  • Interfaces: They are also known as Contracts and are a way of defining the methods that a class should provide, if it implements that interface. Interfaces do not contain any implementation details; they are merely contracts. So, for instance, if a class implements JsonableInterface, it needs to have a toJson() method.

  • Anonymous functions: They are also known as closures and were introduced in PHP 5.3. Somewhat reminiscent of JavaScript, they help you produce shorter code, and you will use them extensively when building Laravel applications to define routes, events, filters, and in many other instances. The following is an example of an anonymous function attached to a route: Route::get('hi', function() { return 'hi'; });.

  • Overloading: Also called dynamic or magic methods, they allow you to call methods such as whereUsernameOrEmail($name, $email) that were not previously defined in a class. These calls are handled by the __call() method, which then tries to parse the name to execute one or more known methods. In this case ->where('username', $username)->orWhere('email', $email).

  • Shorter array syntax: Since PHP 5.4, a shorter array syntax has been introduced. Instead of writing array('primes' =>array(1,3,5,7)), it is now possible to write ['primes'=>[1,3,5,7]]. Although we will use the old syntax in this book, you will probably come across the new syntax on the Web. If your server supports PHP 5.4, there is no reason not to use them.


Laravel's main features and sources of inspiration

Let us now look at what you get when you start a project with Laravel and how these features can help you boost your productivity:

  • Modularity: Laravel was built on top of over 20 different libraries and is itself split up into individual modules. Tightly integrated with Composer Dependency Manager, it can be updated with ease.

  • Testability: Built from the ground up to ease testing, Laravel ships with several helpers that let you visit routes from your tests, crawl the resulting HTML, ensure that methods are called on certain classes, and even impersonate authenticated users.

  • Routing: Laravel gives you a lot of flexibility when you define the routes of your application. For example, you may manually bind a simple anonymous function to a route with an HTTP verb, such as GET, POST, PUT, or DELETE. This feature is inspired by micro-frameworks, such as Sinatra (Ruby) and Silex (PHP). Moreover, it is possible to attach filter functions that are executed on particular routes.

  • Configuration management: More often than not, your application will be running in different environments, which means that the database or e-mail server credentials settings or the displaying of error messages will be different when your app is running on a local development server than when it is running on a production server. Laravel lets you define settings for each environment and then automatically selects the right settings depending on where the app is running.

  • Query builder and ORM: Laravel ships with a fluent query builder, which lets you issue database queries with a PHP syntax where you simply chain methods instead of writing SQL. In addition to this, it provides you with an Object relational mapper (ORM) and ActiveRecord implementation, called Eloquent, which is similar to what you would find in Ruby on Rails to help you define interconnected models. Both the query builder and the ORM are compatible with different databases, such as PostgreSQL, SQLite, MySQL, and SQL Server.

  • Schema builder, migrations, and seeding: Also inspired by Rails, these features allow you to define your database schema with PHP code and keep track of any changes with the help of database migrations. A migration is a simple way of describing a schema change and how to revert to it. Seeding allows you to populate selected tables of your database, for example, after running a migration.

  • Template engine: Partly inspired by the Razor template language in ASP.NET MVC, Laravel ships with Blade, a lightweight template language with which you can create hierarchical layouts with predefined blocks where dynamic content is injected.

  • E-mailing: With its Mail class, which wraps the popular SwiftMailer library, Laravel makes it very easy to send an e-mail, even with rich content and attachments, from your application.

  • Authentication: Since user authentication is such a common feature in web applications, Laravel provides you with the tools to register, authenticate, and even send password reminders to users.

  • Redis: It is an in-memory key-value store that has a reputation for being extremely fast. If you give Laravel a Redis instance that it can connect to, it can use it as a session and general-purpose cache and also give you the possibility to interact with it directly.

  • Queues: Laravel integrates with several queue services, such as Amazon SQS and IronMQ, to allow you to delay resource-intensive tasks, such as the e-mailing of a large number of users, and run them in the background rather than keep the user waiting for the task to complete.

Expressiveness and simplicity

At the heart of Laravel's philosophy is simplicity and expressiveness. This means that particular attention has been given to the naming of classes to effectively convey their actions in plain English. Consider the following code example:


Route::get('area/{id}', function($id){
  if(51 == $area and !Auth::check()) {
    return Redirect::guest('login');
  } else {
    return "Welcome to Area " . $area;
})->where('id, '[0-9]+');


Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you.

Even though we have not even installed Laravel or presented its routing functions yet, you will probably have a rough idea of what this snippet of code does. Expressive code is more readable for someone new to a project, and it is probably also easier to learn and remember for you.

Prettifying PHP

The authors of Laravel have gone on to apply these principles to existing functions as well. A prime example is the File class, which was created to make file manipulations:

  • more expressive: To find out when a file was last deleted, use File::lastModified($path) instead of filemtime(realpath($path)) To delete a file, use File::delete($path) instead of @unlink($path), which is the standard PHP equivalent.

  • more consistent: Some of the original file manipulation functions of PHP are prefixed with file_, while others just start with file; some are abbreviated and other are not.

  • more testable: Many of the original functions can be tricky to use in tests due to the exceptions they throw and also because they are more difficult to mock.

  • more feature complete: This is achieved by adding functions that did not exist before, such as File::copyDirectory($directory, $destination).

There are very rare instances where expressiveness is sacrificed for brevity. This is the case for commonly used shortcut functions, such as e(), that escape html entities or dd() and which you can use to halt the execution of the script and dump the contents of one or more variables.

Responsibilities, naming, and conventions

At the beginning of this chapter, we pointed out that one of the main issues with standard PHP applications was the lack of a clear separation of concerns; business logic becomes entangled with the presentation and data tier. Like many other frameworks that favor convention over configuration, Laravel gives you a scaffolding with predefined places to put code in. To help you to eliminate trivial decisions, it expects you to name your variables, methods, or database table names in certain ways. It is, however, far less opinionated than a framework like Ruby on Rails and in areas like routing, where there is often more than one way to solve a problem.

We have also pointed out that Laravel is an MVC framework. Do not worry if you have not used this architecture pattern before, in a nutshell, this is what you need to know about MVC in order to be able to build your first Laravel applications.

  • Models: Just think of the models as entities of your system. Very often, but not always, they correspond to tables in your database. As we will see, all that is required to define a model is to create a new class that extends the Eloquent class. While the class name is defined with a singular noun in CamelCase, the corresponding table at the database level will by convention have to be the pluralsnake_case version of that class name. Thanks to the inflection libraries it uses, Eloquent will know that a model called VisitedCountry corresponds to the visited_countries table in the database. Laravel will also expect the primary key to be called id, and by default it will look for the created_at and edited_at fields that it updates automatically. Like every other part of Eloquent, and in accordance with the convention over configuration paradigm, if the default behavior is not quite working for you, you can always choose to override it. Models also contain information about how they relate to other models. Using the Active Record terminology, it is possible to define the belongsTo, hasMany, and belongsToMany relationships.

  • Controllers or routes: There are two types of controllers in Laravel, standard controllers and resource controllers. Their job is to make sense of the incoming requests and to send an appropriate response. Both adhere to slightly different conventions. Traditional controllers are similar to what you would find in frameworks such as CodeIgniter, where a detail action that takes one parameter and which lives in the Projects controller could, by convention, be reached at /projects/detail/123. Resource controllers, on the other hand, allow you to define the RESTful controllers that respond to the different HTTP verbs, such as GET, POST, PUT, and DELETE. Lastly, for smaller and simpler applications, it is possible to bypass controllers altogether and write the entire application logic in routes.

  • Views or Templates: Views are responsible for displaying the data that the controller received from the model. They can be conveniently built using the Blade template language or simply using standard PHP. The file extension of the view, either .blade.php or simply .php, determines whether or not Laravel treats your view as a Blade template when it renders it.

The following diagram illustrates the interactions between all the constituent parts:

While it will still be possible to write unstructured code and go against the MVC paradigm and the framework's conventions, it will often involve more effort on the developer's part.

Helping you become a better developer

Laravel's design decisions, and in particular, the way in which it inspires developers to write framework-agnostic code promises it a bright future. In addition to this, its community is probably one of its strongest assets; it is possible to get answers within minutes on forums, IRC, and Twitter.

However, frameworks come and go, and it is hard to predict when Laravel will lose its steam and be supplanted by a better or more popular framework. However, Laravel will not only make you more productive in the short term, it also has the potential to make you a better developer in the long run. By using it to build web applications, you will indirectly become more familiar with the following concepts, all of which are highly transferable to any other programming language or framework. These include the MVC paradigm and Object-oriented programming design patterns, the use of dependency managers, testing and dependency injection, and the power and limitations of ORMs and database migration.

It will also inspire you to write more expressive code with descriptive DocBlock comments that facilitate the generation of documentation as well as the future maintenance of the application.


Structure of a Laravel application

In the next two chapters, we will be installing Laravel and creating our first application. Any new project already has a complete directory tree and even some placeholder files to get you up and running in very little time. This structure is a great starting point, but as we will see in the final chapter of this book, it is also customizable. Here is what it looks like:

./app/                     # Your Laravel application
  ./app/commands/          # - Command line scripts
  ./app/config/            # - Configuration files
  ./app/controllers/       # - Controllers
  ./app/database/          # - Database migrations and seeders
  ./app/lang/              # - Localisation variables
  ./app/models/            # - Classes used to represent entities
  ./app/start/             # - Startup scripts
  ./app/storage/           # - Cache and logs directory
  ./app/tests/             # - Test cases
  ./app/views/             # - Templates that are rendered to HTML
  ./app/filters.php        # - Filters executed before/after a request
  ./app/routes.php         # - URLs and actions

./bootstrap/               # Application bootstrapping scripts

./public/                  # Document root
  ./public/.htaccess       # - Sends incoming requests to index.php
  ./public/index.php       # - Starts Laravel application

./vendor/                  # Third-party dependencies installed through Composer

./artisan*                 # Artisan command line utility

./composer.json            # Project dependencies

./phpunit.xml              # Test configuration file for PHPUnit

./server.php               # Local development server

Like the rest of Laravel, the naming is expressive, and it is easy to guess what each folder is for. On the first level, there are four directories, app/, bootstrap/, public/, and vendor/. All your server-side code will reside in the app/ directory, inside which you will find the three directories that hold the files for the controllers, models, and views. We will explore the responsibilities of each directory further in the next chapters.

The application container and request lifecycle

Whether you are a beginner in PHP or an experienced developer in a different language, it might not always be obvious how an HTTP request reaches a Laravel application. Indeed, the request lifecycle is fundamentally different from plain PHP scripts that are accessed directly by their URI (for example, GET

The public/ directory is meant to act as the document root; in other words, the directory in which your web server starts looking after every incoming request. Once URL rewriting is properly set up, every request that does not match an existing file or directory hits the /public/index.php file. The job of this file is to register the Composer class autoloader, which tells PHP where to look for any classes that are called. It then bootstraps the application by setting its environment based on the host name and binding the different paths of your application. Once that is done, it simply instantiates a new application container, which is in turn responsible for dealing with the incoming request. This application container uses an HTTP verb and request URL (for example, POST /comments) and maps it to the correct controller action or route.

Exploring Laravel

In this chapter, we are only covering the general mechanisms of how Laravel works, without looking at the detailed implementation examples. For the majority of developers who just want to get the job done, this is sufficient. Moreover, it is much easier to delve into the source code of Laravel once you have already built a few applications. Nevertheless, here are some answers to the questions that might crop up when exceptions are thrown or when you navigate through the source code. In doing so, you will come across some methods that are not documented in the official guide, and you might even be inspired to write better code.

Browsing the API ( can be somewhat intimidating at first. But it is often the best way to understand how a particular method works under the hood. Here are a few tips:

  • The Illuminate namespace does not refer to a third-party library. It is the namespace that the author of Laravel has chosen for the different modules that constitute Laravel. Every single one of them is meant to be reusable and used independently from the framework.

  • When searching for a class definition, for example, Auth, in the source code or the API, you might bump into Façade, which hardly contains any helpful method and only acts as a proxy to the real class. This is because almost every dependency in Laravel is injected into the application container when it is instantiated.

  • Most of the libraries that are included in the vendor/ directory contain a README file, which details the functionality present in the library (for example, vendor/nesbot/carbon/

Moving from Version 3 to Version 4

The rise in popularity of Laravel started with its third version. Although most of the core features have been ported to version 4, if you have already written applications with Laravel 3, and you are reading this book to get up to speed with the changes and maybe migrate your app, here are the main changes that you need to be aware of:

  • Packages are the new bundles: Laravel 3 had a thriving ecosystem of plug-ins, called bundles. The PHP community is trying to steer away from framework-specific packages since they complicate future maintenance, and release more generic packages instead. If you happen to stumble upon a Laravel bundle that seems to solve a problem, you are having in your applications, unfortunately it will not work with Laravel 4. To replace them, it now encourages the use of packages, many of which are framework-agnostic.

  • Composer all over: The next chapter will explore this in more detail, but Laravel 4 uses composer to manage its various dependencies and keep them up to date.

  • New coding conventions: As mentioned previously, Laravel 4 adheres to the PSR-0 and PSR-1 standards. The most notable change is the switch to camelCase methods and class names, where User::where_email_and_active($email, true) became User::whereEmailAndActive($email,true) and User_Controller became UserController.

  • Dependency injection: Laravel 4 has been rewritten to heavily rely on dependency injection. This makes it easy to swap out entire classes and facilitates testing.

  • Documentation: The new documentation has been simplified and the topics have been regrouped. Compared to the 3.0 documentation, it is slightly terser in some areas. The API, generated with ApiGen, also has a fresh look and is a joy to browse.

  • Renamed methods: Other changes to consider, especially when migrating an existing application, is the renaming of certain methods URL::to_route was shortened to URL::route.



In this chapter, we have introduced the main characteristics of Laravel 4 and how it can help you to write more structured applications while reducing the amount of boilerplate code. We have also explained the concepts and PHP features used by Laravel, and you should now be well equipped to get started and write your first application! In the next chapter we will learn how to install and use Composer, a dependency manager for PHP, which will install Laravel and its dependencies for you.

About the Author

  • Raphaël Saunier

    Raphaël Saunier works as a full-stack Web Developer for Information Architects in Zürich, Switzerland. He holds a degree in Information Management for Business from University College London.

    He is always looking for excuses to learn and play with new technologies, tools, and techniques. He is also able to make pragmatic decisions that take into account the strengths and weaknesses of the many well-established tools at the disposal of web developers.

    A strong advocate of Laravel, Ember.js, Vim, and PostgreSQL when he is among developers, he is also passionate about teaching programming and general computer literacy to people of all ages.

    Browse publications by this author

Latest Reviews

(1 reviews total)
Book Title
Access this book, plus 7,500 other titles for FREE
Access now