in Laravel, Our Authors

What’s so great about Laravel?

Several people asked me to compare “some PHP framework” with Laravel. Now because I’ve used several frameworks and not every one, I will write in this article what’s so great about Laravel, and you compare it with some other PHP framework that you know.

Laravel is a very unique framework with very strong branding, so almost everything special about Laravel has a unique name. Not everything below is about code, its about the framework, community and ecosystem.

Composer

Composer is a dependency manager for PHP. It’s not Laravel specific, but Laravel doesn’t work without it.

Composer (with Packagist) contains thousands of PHP packages from community, most of them loosely coupled and can be easily added to your application without problems. So you don’t have to reinvent the wheel, and the framework isn’t gonna stop you from using existing solutions.

Composer handles autoloading PHP Classes using any configuration from classmap, files, or PSR-0 or PSR-4.

Now because Composer uses versioning you can easily lock the versions of packages for your application, so that you can ensure the same code is running anywhere you deploy your application.

Its easy to get started with Laravel, just install Composer and run:

composer create-project laravel/laravel

PHP 5.4

Laravel 5 requires PHP 5.4 and Laravel 4 requires PHP 5.3. And when I say requires, it means Laravel fully utilises all the new features of PHP like Closures , Namespaces, Traits and others.

Laravel is not some PHP 4 framework adapted to use Classes for PHP 5, it is developed with strong Object Oriented paradigms and you can really get to use the latest of PHP.

PHP requirement also mean that your code can use the performance enhancements of newer PHP runtime.

Dotenv

Where do you keep the secret information of your app like database password, email login and other things? Laravel 5 uses a well known .env file that many frameworks form other programing languages use. This is a file in which you define key and value pairs for any secret information you have.

For example, your .env file could look like this:

APP_ENV=production
DB_HOST=127.0.0.1
DB_DATABASE=laraveldb
DB_USERNAME=laravelapp
DB_PASSWORD=str0ngP4sw0rd

And you could setup your config files like this:

'connections' => array(  
    'mysql' => array(
        'driver'    => 'mysql',
        'host'      => env('DB_HOST'),
        'database'  => env('DB_DATABASE'),
        'username'  => env('DB_USERNAME'),
        'password'  => env('DB_PASSWORD'),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ),
),

So you create this file locally and create a different one on your production server, now you commit your app and push without worrying about database or any other important secret data.

Loading of .env file is automatically handled by Laravel with Dotenv library.

PSR-4

Laravel is the first framework to support PSR-4. Out of the box, Composer will auto-load all classes within the app directory using the PSR-4 auto-loading standard.

This means that you can have a single namespace for your application and structure it the way you want and think is logical to you, so Laravel is not forcing you to put certain files into certain folders.

This is the default app directory with App namespace:

app
├── Console
│   └── InspireCommand.php
├── Http
│   ├── Controllers
│   │   ├── Auth
│   │   │   ├── AuthController.php
│   │   │   └── PasswordController.php
│   │   └── HomeController.php
│   ├── Middleware
│   │   ├── AuthMiddleware.php
│   │   ├── BasicAuthMiddleware.php
│   │   ├── CsrfMiddleware.php
│   │   ├── GuestMiddleware.php
│   │   └── MaintenanceMiddleware.php
│   └── Requests
│       └── Auth
│           ├── LoginRequest.php
│           └── RegisterRequest.php
├── Providers
│   ├── AppServiceProvider.php
│   ├── ArtisanServiceProvider.php
│   ├── ErrorServiceProvider.php
│   ├── EventServiceProvider.php
│   ├── LogServiceProvider.php
│   └── RouteServiceProvider.php
└── User.php

You can see it has some defaults but you can put classes wherever you want, which makes it very easy.

You can always change app namespace with the command:

php artisan app:name YourNamespace

This command will go through all your files and change the namespace declaration in them.

IOC Container – Core extensions

The Laravel inversion of control container is a powerful tool for managing class dependencies. Dependency injection is a method of removing hard-coded class dependencies. Instead, the dependencies are injected at  run-time, allowing for greater flexibility as dependency implementations may be swapped easily.

You can use IOC container for your app to make everything injectable and easily testable using mocks.

IOC container can resolve classes without any configuration at all. For example:

class FooBar {

    public function __construct(Baz $baz)
    {
        $this->baz = $baz;
    }

}

You see, the class Baz is autoinjected into class FooBar. Practical usage would be inside controllers, like this:

class OrderController extends BaseController {

    public function __construct(Order $orders)
    {
        $this->orders = $orders;
    }

    public function getIndex()
    {
        $all = $this->orders->all();

        return View::make('orders', compact('all'));
    }

}

You can see in this example Order class is injected into OrderController without any additional setup.

But newer Laravel has something even greater and that is called Method Injection. This is Dependency injection on per method basis.

For example, you can see this class in a simpler way:

class OrderController extends BaseController {

    public function getIndex(Order $orders)
    {
        $all = $orders->all();

        return View::make('orders', compact('all'));
    }

}

You can add as many dependencies on per class or per method basis as you like, and IOC container will resolve it for you.

Because everything is injected in Laravel, you can easily swap out anything from the core of the framework.

Form requests

Laravel has this awesome feature called Form requests, it is request validation for your controllers. Its not just some data validation but full request processing.

Form requests are combined with Method Injection functionality to add boilerplate free method of validating user input. For example you can see RegisterRequest:

<?php namespace App\Http\Requests;

class RegisterRequest extends FormRequest {

    public function rules()
    {
        return [
            'email' => 'required|email|unique:users',
            'password' => 'required|confirmed|min:8',
        ];
    }

    public function authorize()
    {
        return true;
    }

}

This request has rules for data validation and also it has authorization functionality which says who can use this Request, and in this example it is everyone, so everyone can register using email and password fields.

To use this request you just need to type hint the request object inside your controller and you get request validation in a very easy way.

<?php namespace App\Http\Controllers\Auth;

use Illuminate\Routing\Controller;
use Illuminate\Contracts\Auth\Guard;
use App\Http\Requests\Auth\LoginRequest;
use App\Http\Requests\Auth\RegisterRequest;

class AuthController extends Controller {

	protected $auth;

	public function __construct(Guard $auth)
	{
		$this->auth = $auth;
	}

	public function register(RegisterRequest $request)
	{
		// Registration form is valid, create user...
		$this->auth->login($user);

		return redirect('/');
	}
}

So you can see that this controller here doesn’t have any glue code or any validation code contained in it, and it’s all separate and clean.

Form requests have redirect functionality when validation fails, messages for views and other.

Eloquent

Eloquent ORM included in Laravel is the most powerful implementation of ActiveRecord pattern in PHP.  Except for regular CRUD operations it has Soft Deleting, Query Scopes, Relationships, Accessors and Mutators, Date mutators, Model Observers, and many many more.

And guess what, you don’t even need Laravel to use it. You can easily add Laravel database layer with Eloquent to your non Laravel PHP project. Just see the https://github.com/illuminate/database to set it up for your project.

Not to mention the hundreds of Eloquent extensions like Baum nested set, TranslatableArdent Model Validations, Database Backup Manager, MongoDB and many others.

Release cycle

Laravel has very predictable release cycle. Every 6 months you can expect a new version of Laravel. It is released 1 month after Symfony releases.

You get either a feature release or a whole new release number. Bugfix releases are released every few months. This is good, because framework is being developed very fast and you can expect the latest security and other improvements as soon as possible.

Major releases are mostly easy to migrate to and you probably won’t have any issues upgrading, but because Laravel is a great foundation for anything you can even stay on the same release for a full year and see that the version you’re using is still receiving bug fixes and improvements.

SSH tasks

Laravel includes a simple way to SSH into remote servers and run commands, allowing you to easily build tasks that work on remote servers. With a little configuration you can run your tasks like:

SSH::into('production')->run(array(
    'cd /var/www',
    'git pull origin master',
));

Or you can use a different server connection, like:

SSH::into('staging')->run(array(
    'cd /var/www',
    'git pull origin master',
));

You can also download files:

SSH::into('staging')->get($remotePath, $localPath);
$contents = SSH::into('staging')->getString($remotePath);

Or upload:

SSH::into('staging')->put($localFile, $remotePath);
SSH::into('staging')->putString($remotePath, 'Foo');

So you see what you can build with this tool. You can automate several tasks that you need to do for maintenance or deployment of your server, or anything else.

Flysystem

Flysystem is an awesome package from The League of Extraordinary Packages for managing Filesystems. It’s a filesystem that uses connectors and with which you can easily interact with local, awss3, dropbox, rackspace, and other filesystems in the cloud.

How easy, see this:

// Write Files
File::put('filename.txt', 'contents');

// Read Files
$contents = File::get('filename.txt');

// Check if a file exists
$exists = File::exists('filename.txt');

// Delete Files
File::delete('filename.txt');

// Create Directories
File::makeDirectory('nested/directory');

// Delete Directories
File::deleteDirectory('path/to/directory');

And you can use this same API for any filesystem you want to use. Flysystem comes built-in into Laravel and you can use File class.

Elixir

If you have been using the latest Frontend technologies in the last few years, you probably use a preprocessor for your CSS and JavaScript files, but if you haven’t Laravel has you covered.

You need to have the most optimized version of your application online possible. That means you have to minify and combine CSS and JavaScript files.

Except for using some PHP package for that, Laravel comes with Elixir package for NodeJS Gulp task runner. So you can use all that NodeJS and Gulp goodness you like.

You start Gulp watch task and Elixir takes care of everything for you. If you’re using LESS and CoffeeScript your setup can be like this:

var elixir = require('laravel-elixir');
elixir(function(mix) {
    mix.less()
       .coffee()
       .routes()
       .events()
       .phpUnit();
});

This configuration is gonna compile your less and coffee files, and also scan for routes and events in your application. Also it’s going to run unit tests after every change of PHP files.

This is so easy to setup. You just need to put your less and coffee files into /resources/assets folder. For less /resources/assets/less and for coffee /resources/assets/coffee folder and you have everything setup from then on.

You can then reference built files in your views, and build files later for production environment.  You should know Elixir supports even more then what’s shown in the example.

compiled.php

Every fully featured framework has to load itself with thousands of files and declarations. For the most part it’s all handled by Composer auto-loading but for more common files Artisan can build a compiled.php file which is loaded on every request which combines all the required classes your App uses.

So the most common files and classes are then compiled into one single file, which dramatically decreases load time of the application. Also when there are your files that need to be loaded on every request you can also configure which files to compile to compiled.php.

This file is then being optimized by PHP runtime so that you can skip the performance hit of loading of thousands of files on your production environment.

HHVM

When it gets to a point that you want to get more performance from your PHP code, you can switch the PHP environment to highly optimized HHVM Facebook’s PHP runtime.

Laravel is one of the first frameworks to support HHVM and it runs 100% of unit tests on HHVM so you can be sure that you can easily switch PHP with HHVM for your app and get even more performance.

http://hhvm.com/frameworks/

Homestead

Laravel Homestead is an official, pre-packaged Vagrant “box” that provides you a wonderful development environment without requiring you to install PHP, HHVM, a web server, and any other server software on your local machine

Its a virtual machine with everything setup in it, with included software:

  • Ubuntu 14.04
  • PHP 5.6
  • HHVM
  • Nginx
  • MySQL
  • Postgres
  • Node (With Bower, Grunt, and Gulp)
  • Redis
  • Memcached
  • Beanstalkd
  • Laravel Envoy
  • Fabric + HipChat Extension

So you just run vagrant up and go to locahost:8000 and see your app running. Your code locally is being shared with virtual machine and you don’t need to install all the listed software at all, you just need Laravel and your code editor.

So later when you try to create a VPS server you can use Laravel Settler project to create the exact same server as your Homestead environment.

This is just awesome, and it saves so much time and frustration setting up local environment for development.

Stack middleware

Laravel uses StackPHP’s implementation of Symfony’s HttpKernel. This means we can add our own middleware to our HTTP layer!

Middlewares are request processors with which you can add functionality to HTTP requests, before, after or even modifying Requests or modifying Responses.

For example look at the MaintenanceMiddleware:

<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Response;
use Illuminate\Contracts\Routing\Middleware;
use Illuminate\Contracts\Foundation\Application;

class MaintenanceMiddleware implements Middleware {

	/**
	 * The application implementation.
	 *
	 * @var Application
	 */
	protected $app;

	/**
	 * Create a new filter instance.
	 *
	 * @param  Application  $app
	 * @return void
	 */
	public function __construct(Application $app)
	{
		$this->app = $app;
	}

	/**
	 * Handle an incoming request.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 * @return mixed
	 */
	public function handle($request, Closure $next)
	{
		if ($this->app->isDownForMaintenance())
		{
			return new Response('Be right back!', 503);
		}

		return $next($request);
	}

}

You can see how the maintenance check functionality is added to every request inside the handle method. You see that $next($request) line, this is how the request is being passed to next Middleware class and latter to the framework itself.

You can use Middlewares to add any functionality that you need in your HTTP layer.

Default Laravel comes with AuthMiddleware, GuestMiddleware, MaintenanceMiddleware, CsrfMiddleware, and you can easily add your own Middleware, or you can use one of available here like HttpCache, Geoip, CORS, OAuth, Turbolinks and others.

Cashier

Laravel Cashier provides an expressive, fluent interface to Stripe’s subscription billing services. It handles almost all of the boilerplate subscription billing code you are dreading writing.

In addition to basic subscription management, Cashier can handle coupons, swapping subscription, subscription “quantities”, cancellation grace periods, and even generate invoice PDFs.

It is an official package by Laravel developers not included by default. See how easy it is to use Cashier, to subscribe a user:

$user = User::find(1);
$user->subscription('monthly')->create($creditCardToken);

// with coupon
$user->subscription('monthly')
     ->withCoupon('code')
     ->create($creditCardToken);

// Trial ends
$user->trial_ends_at = Carbon::now()->addDays(14);
$user->save();

// Cancel
$user->subscription()->cancel();

// Resume
$user->subscription('monthly')->resume($creditCardToken);

// Checking status
if ($user->subscribed())
{
    //
}

// On trial
if ($user->onTrial())
{
    //
}

// Is canceled
if ($user->cancelled())
{
    //
}

// Is on grace period
if ($user->onGracePeriod())
{
    //
}

// Was ever subscribed
if ($user->everSubscribed())
{
    //
}

// Check on what plan user is on
if ($user->onPlan('monthly'))
{
    //
}

You can use Invoices, and many other functionalities of Stripe.

Rocketeer

Rocketeer is a fast and easy deploying tool for modern developers. It is inspired by Laravel and can be used in Laravel and also for any PHP project.

It can deploy any project from small HTML/CSS websites to large PHP applications, or any application in any programing language.

With Rocketeer you can deploy latest, current, staging environments easily, and have an option to rollback to older release whenever you have an issue.

With a little configuration, running Rocketeer in Laravel is as easy as running artisan and one of these commands:

deploy
  deploy:check                 Check if the server is ready to receive the application
  deploy:cleanup               Clean up old releases from the server
  deploy:current               Display what the current release is
  deploy:deploy                Deploys the website
  deploy:flush                 Flushes Rocketeer's cache of credentials
  deploy:ignite                Creates Rocketeer's configuration
  deploy:plugin-config         Publishes the configuration of a plugin
  deploy:plugin-install        Install a plugin
  deploy:plugin-list           Lists the currently enabled plugins
  deploy:rollback              Rollback to the previous release, or to a specific one
  deploy:setup                 Set up the remote server for deployment
  deploy:strategies            Lists the available options for each strategy
  deploy:teardown              Remove the remote applications and existing caches
  deploy:test                  Run the tests on the server and displays the output
  deploy:update                Update the remote server without doing a new release

It is great to use such a stable and well thought-out deployment process.

Unifying PHP

Laravel is truly unifying PHP community by using more then 23 packages from the wider PHP community. Using the “best of the best” PHP packages allows for greater interaction between Laravel and the wider PHP community.  Among the included packages there are:

Dotenv:  PHP version of the original Ruby dotenv, loading of enviroment variables.

Carbon: An expressive date library by Brian Nesbitt.

Predis: A robust Redis client authored by Daniele Alessandri.

Phenstalk: Full-featured PHP client for the Beanstalked queue.

SuperClosure: Written by Jeremy Lindblom, this powerful library allows you to serialize and unserialize PHP Closures.

Whoops: Displays the pretty error pages and stack traces while Laravel is in development mode.

Monolog: The de-facto standard of PHP logging libraries.

Boris: Really slick PHP REPL which powers the amazing “tinker” console command.

PasswordCompat: Powers the secure Bcrypt hashing that is used by default by Laravel.

Symfony HttpFoundation: Extremely robust HTTP abstraction. Well tested and proven in many large, real-world applications.

Symfony Routing: This package powers the compilation of Laravel routes to regular expressions.

Symfony HttpKernel:  Contains the HttpKernelInterface which is used as the bottom-level abstraction for a Laravel application.

Symfony BrowserKit: Slick functional testing.

StackPHP: This project outlines a structure for building reusable, framework agnostic middlewares at the HTTP layer.

Laracasts – Jeffery Way

Laracasts is a resource, not just for Laravel developers, but for modern PHP, in general. It features over 300 screencasts for solving any issue or implementing almost anything with Laravel.

Almost everything mentioned in this article can be learned on Laracasts. It is an awesome teaching resource made by Jeffery Way. Jeffery Way! From Envato! Jeffery Way is a very well respected PHP community member and a great teacher.

With Laracasts Laravel community really stands out in PHP ecosystem as nothing comparable can be found for other PHP frameworks.

Liferaft

Creating issues on GitHub is the best way to get your issue known and resolved. But what you do when you can’t explain the problem you have? What when you only get this problem in your code in your custom app?

Liferaft is a CLI tool installed with Composer that provides the best way to contribute to Laravel or to create an issue.

You just run some Liferaft command and it creates a Laravel application and you just put your code that recreates the problem for you and you run another Liferaft command to create the issue on Github.

For example:

liferaft new my-bug-fix

And recreate the issue inside this application. The only thing from you is needed to fill in liferaft.md with explanation of your problem, and you could provide a unit test how it should behave, and then:

liferaft throw

Then maintainer can run your application and see the problem you’re having.  This solves so many problems and takes much less time for maintainers of the Framework to respond to you and resolve the problem you’re having.

You can read more about Liferaft here.

Community

I mention community last, because every framework now has a big and friendly community, and Laravel is the same. People maintaining and people developing Laravel packages are very friendly and you can easily contribute to any package and have your changes merged very soon.

It helps to have a big community and you should know Laravel was listed as the most popular PHP framework in 2013, followed by Phalcon, Symfony2, CodeIgniter and as of August 2014 Laravel is the most popular and watched PHP project on GitHub.

Also I have to mention laravel.io which many users use and you can find discussions, answers to questions, jobs (https://larajobs.com) and anything else you need.

Conclusion

Laravel users know that I could mention so much more special things about Laravel, but this should be enough. You should know that you’re always welcome to use and contribute and even use parts of this great PHP framework.

Share this ...Tweet about this on TwitterShare on FacebookEmail this to someoneShare on RedditShare on Google+Share on LinkedInPin on Pinterest
  • Pingback: What’s so great about Bower? - Legacy Blog()

  • mirkinoid

    great article! watching at laravel for some time, definitely going to use it in my next project

  • Bonbon Lang-es

    New to laravel. I there a Laravel way to unittest javascript/jquery codes?