25 Laravel Tips and Tricks
- Transfer
There was a time, quite recently, when PHP and its community hated it. The main joke was about how terrible PHP is.
Yes, unfortunately, the community and ecosystem were simply below the level of other modern languages. It seemed that the purpose of PHP was to live most of the time in the form of messy WordPress themes.
But later, surprisingly, things began to change - and quickly enough. As if while the witch was stirring the pot, innovative projects began to appear from nowhere. Probably the most notable project was Composer: the most comprehensive dependency manager for PHP (like the Bundler for Ruby or NPM for Node.js). In the past, PHP developers were forced to cope with PEAR (which was a scary dream, actually), now, thanks to Composer, they can just update the JSON file, and immediately pull up all the necessary dependencies. Here is the profiler, there is the testing framework. It takes seconds.
In the crowded world of PHP frameworks, just as CodeIgniter began to run out of steam, Taylor Otwell's Laravel framework emerged from the ashes to become the darling of society. With such simple and elegant syntax, creating applications with Laravel and PHP was absolutely fun! Further, with the fourth version of the framework that made full use of Composer, it finally seemed that for the community, all things fell into place.

Want migrations (version control of the database)? Done! How about a powerful implementation of Active Record? Of course, Eloquent will do everything for you. How about being able to test? Of course! Routing (routing)? By all means! What about a well-tested HTTP layer? Thanks to Composer, Laravel uses many excellent Symfony components. When it comes to business, there is every chance that Laravel can already offer you this!

Previously, PHP was like a game of Jenga - one cube from falling apart - all of a sudden, thanks to Laravel and Composer, a light came on at the end of the tunnel. So we will remove all the hints, and let's dig into everything that the framework has to offer!
Laravel offers one of the most powerful Active Record implementations in the PHP world. Say you have an orders table along with an Eloquent Order model.
We can easily execute any number of queries to the database using simple and elegant PHP code. No need to randomly scatter SQL. Let's get all the orders.
Done! Or maybe these orders should be sorted by date. Easy:
And what if, instead of receiving the record, we need to save the new order to the database. Of course, we can do this.
Done! With Laravel, tasks that used to be cumbersome to complete are now laughably simple.
* - Eloquent - the name of the implementation of Active Record in Laravel, as well as translated from English is eloquent.
Laravel is unique in that it can be used in many ways. Prefer simpler and Sinatra-like routing? Laravel can do this easily using anonymous functions.
This may be useful for small projects and APIs, but there is a good chance that you will need controllers for most of your projects. Okay, Laravel can do that too.
Done! Notice how Laravel grows as you need? Fixture level is what makes the framework so popular today.
What do we do in objects when we need to define relationships? For example, the task belongs to the user exactly. How to specify this in Laravel? Assuming that the required tables in the database are created, we just need to refer to the related Eloquent models.
All is ready! Let's get all the user tasks with id = 1. To do this, we need only 2 lines of code.
However, since we indicated the relationship on both sides, if we want to get the user who is assigned this task, this is also easy to do.
Very often, it will be useful to associate a form with a model. An obvious example is when you want to change some record in the database. Having connected the form with the model, we can instantly fill out the form fields with data from the database.
Since the form is associated with an object of the Order model, data from the table will be displayed in the fields. So simple!
Too many queries to the database, and quickly enough your application can become like black molasses. Fortunately, Laravel provides a simple mechanism for caching these requests using just one method call.
Let's get all the questions from the database, but at the same time cache the request, since this table is unlikely to change often.
That's all! Now, over the next hour, this request will be stored in the cache, and the database will be untouched.
You will encounter situations when several templates require some variable or piece of data. A good example of this is the navigation menu, which displays a list of tags.
To keep controllers with minimal code, Laravel offers template composers (views) to manage these things.
Using this piece of code, at any time when the layouts / nav.blade.php file is loaded, it (the file) will have access to the $ tags variable.
Laravel takes a very simple authorization approach. Just pass the array of data that you most likely received from the login form to Auth :: attempt (). If the provided array matches what is stored in the users table, the user will be immediately authorized.
What if I need to exit when going, for example, to the / logout URI?
Working RESTfully at Laravel is also very easy! To declare a controller a resource, simply call Route :: resource () as follows.
This code will register 8 routes.
Further, OrdersController can be generated from the command line:
In this controller, each method will correspond to one of the routes described above. For example, / orders will call the index method, / orders / create - the create method and so on.
Now we have the necessary strength to easily build RESTful applications and APIs.
Yes, PHP is a template language by nature, but it hasn't become too good. However, it's okay. Laravel offers its Blade engine to fill the gap. Just name your templates with the extension .blade.php and they will be parsed accordingly. Now we can do the following:
Since Laravel uses Composer, we immediately have PHPUnit support out of the box. Install the framework and run phpunit from the command line to test.
In addition to this, Laravel offers a number of helpers for some common types of functional tests.
Let's check that the home page returns a 200 response code.
Or maybe we want to check that when the contact form is sent to the server, the user is redirected to the home page with the message.
Part of Laravel 4.1, which was released in November 2013, was the ability to write a console command for Artisan to connect to the server via SSH and perform any actions. Just use the SSH facade:
Pass an array of commands to the run () method, and Laravel will do the rest! Now, since it makes sense to execute commands as Artisan commands, you just need to execute
Laravel offers an elegant implementation of the Observer pattern that you can use anywhere in your application. Subscribe to native events, such as illuminate.query, or start and listen to your own.
Thoughtful use of events will give you many opportunities.
Like most things in Laravel, if you prefer to specify a class name rather than an anonymous function, you can safely do it. Laravel will ruin everything using an IoC container.

The application is growing, and it can become hard to see which routes are described. Especially if you did not pay enough attention to the routes.php file (for example, excessive description of routes).
Laravel offers a convenient routes command that will show all registered routes, along with the controller methods that these routes call.
Think about an event when a user logs into your application. Most likely, a number of side events will occur. The database should be updated, the score should increase, a welcome letter should be sent, and so on. Unfortunately, such actions tend to be time consuming.
Why make users wait for these events to happen if we can send these events to run in the background?
Perhaps the most remarkable thing is that Laravel works great with Iron.io “push” queues. This means that even without experience with workers or demons, we can still use queues. Just describe the route using the php artisan queue: subscribe command, and Iron.io will send data to this URL every time a task is queued. And this route, in turn, will perform the necessary actions.

When validation is needed, Laravel comes to our aid again! Using the Validator class is easy. Just pass the object for validation along with the rules to the make method, and Laravel will do the rest.

Especially if you are using Laravel for the first time, it may be useful to tinker with the kernel. The tinker team will help with this.
Tinker uses the popular component Boris.
Think of migrations as version control of a database. At any time, you can “roll back” migrations, return them, update, and so on. Probably, the power of migrations lies in launching the application into production and simply running the php artisan migrate command to construct the database.
To prepare the schema for the new users table, we can execute:
The command will generate a migration file, which you fill in as you need. As you are ready, the php artisan migrate command will create the table. That's all! Need to roll back the changes? Easy! php artisan migrate: rollback.
Here is an example table for the FAQ table.
Note that the drop () method does the opposite of the up () method. This is what allows you to “roll back” migration. Isn't that a lot easier than tormenting with pure SQL?
Laravel offers a number of generators. But there is also a package called “Laravel 4 Generators”, and it went even further. It can generate resources, files for filling the base, pivot tables and migrations.
In the previous paragraph, we were forced to write the scheme ourselves. But using the generator package, we can execute the command:
And the generator will do the rest. With this command you can prepare and create a new table in the database.
Laravel 4 Generators can be installed through Composer.
A number of cases have already been described when it will be useful to write custom commands. They can be used in building applications, file generation, deploy applications and everything else.
Since this is a common task, Laravel makes the process of creating commands the easiest.
This command will generate the desired template for your custom team. Next, in the newly created file app / commands / MyCustomCommand.php, fill in the name and description.
And, in the fire () method, perform the necessary actions. After that, it remains only to register the command for Artisan, in the file app / start / artisan.php.
Believe it or not, but that's it! Now you can call this command from the terminal.
Laravel makes a lot of use of the Facade template. This makes it possible to use the “static” syntax, which, no doubt, you will like (Route :: get (), Config :: get (), and so on), and at the same time allows you to fully test them.
Since the “underlying” class is resolved through the IoC container, we can easily replace the “lower” classes with our test ones. This allows us to do the following:
Yes, we call shouldReceive directly from the facade. “Behind the scenes,” Laravel uses the Mockery framework. This means that you can absolutely use the facades, and at the same time test absolutely all pieces of code.
Since building forms is often a cumbersome task, the Laravel form builder steps in to facilitate this process, as well as use some of the “style features” associated with form design. Here are some examples:
What about the task of remembering the entered data during the last form submission? Laravel does it automatically!
At the core of Laravel is a powerful IoC container, which is a tool to help manage class dependencies. It is worth noting that he has the power to automatically determine the necessary classes without presets.
Just typehint your dependencies in the constructor, and upon initializing Laravel using the PHP Reflection API, it will correctly read your prompts and try to insert these classes for you.
When you request a class from an IoC container, dependency resolution will happen automatically.
It is important to note that controllers are always requested from the IoC container. Therefore, you can freely typehint for the dependencies of your controllers, and Laravel will try to implement them.
One environment may be suitable for small projects. For other projects, multiple environments are vital! Development, testing, production. All this is vital and each environment requires its own settings.
Perhaps your test environment uses an in-memory database for testing. Maybe your dev environment uses other API keys. And the production environment uses its database connection settings.
Fortunately, Laravel makes our work easier again. Take a look at bootstrap / start.php.
There is a simple demonstration of setting up the local environment, which is based on the hostname of the computer.
In general, this will work. But it is preferable to use environment variables for such things. Don’t worry, this is easy to do in Laravel! Just pass the function to the detectEnvironment method.
Now, if the environment variable is not set (and you set it for production), the environment will be local.
Laravel again uses a very simple configuration approach. Create a folder with the name of the environment in the app / config folder, and any configuration files in this folder will take precedence over others, provided that you are in this environment. For example, you can specify a different API key for the dev environment.
The configuration is fully automatic. Just call the method
When it comes to learning, the Laravel community is infinitely good, despite being young. For a little over a year, half a dozen different books have been published related to Laravel development.
Yes, unfortunately, the community and ecosystem were simply below the level of other modern languages. It seemed that the purpose of PHP was to live most of the time in the form of messy WordPress themes.
But later, surprisingly, things began to change - and quickly enough. As if while the witch was stirring the pot, innovative projects began to appear from nowhere. Probably the most notable project was Composer: the most comprehensive dependency manager for PHP (like the Bundler for Ruby or NPM for Node.js). In the past, PHP developers were forced to cope with PEAR (which was a scary dream, actually), now, thanks to Composer, they can just update the JSON file, and immediately pull up all the necessary dependencies. Here is the profiler, there is the testing framework. It takes seconds.
In the crowded world of PHP frameworks, just as CodeIgniter began to run out of steam, Taylor Otwell's Laravel framework emerged from the ashes to become the darling of society. With such simple and elegant syntax, creating applications with Laravel and PHP was absolutely fun! Further, with the fourth version of the framework that made full use of Composer, it finally seemed that for the community, all things fell into place.

Want migrations (version control of the database)? Done! How about a powerful implementation of Active Record? Of course, Eloquent will do everything for you. How about being able to test? Of course! Routing (routing)? By all means! What about a well-tested HTTP layer? Thanks to Composer, Laravel uses many excellent Symfony components. When it comes to business, there is every chance that Laravel can already offer you this!

Previously, PHP was like a game of Jenga - one cube from falling apart - all of a sudden, thanks to Laravel and Composer, a light came on at the end of the tunnel. So we will remove all the hints, and let's dig into everything that the framework has to offer!
1. Expressive requests *
Laravel offers one of the most powerful Active Record implementations in the PHP world. Say you have an orders table along with an Eloquent Order model.
classOrderextendsEloquent{}
We can easily execute any number of queries to the database using simple and elegant PHP code. No need to randomly scatter SQL. Let's get all the orders.
Order::all();
Done! Or maybe these orders should be sorted by date. Easy:
$orders = Order::orderBy('release_date', 'desc')->get();
And what if, instead of receiving the record, we need to save the new order to the database. Of course, we can do this.
$order = new Order;
$order->title = 'Xbox One';
$order->save();
Done! With Laravel, tasks that used to be cumbersome to complete are now laughably simple.
* - Eloquent - the name of the implementation of Active Record in Laravel, as well as translated from English is eloquent.
2. Flexible routing (routing)
Laravel is unique in that it can be used in many ways. Prefer simpler and Sinatra-like routing? Laravel can do this easily using anonymous functions.
Route::get('orders', function(){
return View::make('orders.index')
->with('orders', Order::all());
});
This may be useful for small projects and APIs, but there is a good chance that you will need controllers for most of your projects. Okay, Laravel can do that too.
Route::get('orders', 'OrdersController@index');
Done! Notice how Laravel grows as you need? Fixture level is what makes the framework so popular today.
3. Relations without problems
What do we do in objects when we need to define relationships? For example, the task belongs to the user exactly. How to specify this in Laravel? Assuming that the required tables in the database are created, we just need to refer to the related Eloquent models.
classTaskextendsEloquent{
publicfunctionuser(){
return$this->belongsTo('User');
}
}
classUserextendsEloquent{
publicfunctiontasks(){
return$this->hasMany('Task');
}
}
All is ready! Let's get all the user tasks with id = 1. To do this, we need only 2 lines of code.
$user = User::find(1);
$tasks = $user->tasks;
However, since we indicated the relationship on both sides, if we want to get the user who is assigned this task, this is also easy to do.
$task = Task::find(1);
$user = $task->user;
4. The relationship of the form with the model
Very often, it will be useful to associate a form with a model. An obvious example is when you want to change some record in the database. Having connected the form with the model, we can instantly fill out the form fields with data from the database.
{{ Form::model($order) }}
<div>
{{ Form::label('title', 'Title:') }}
{{ Form::text('title') }}
</div>
<div>
{{ Form::label('description', 'Description:') }}
{{ Form::textarea('description') }}
</div>
{{ Form::close() }}
Since the form is associated with an object of the Order model, data from the table will be displayed in the fields. So simple!
5. The cache of requests to the database
Too many queries to the database, and quickly enough your application can become like black molasses. Fortunately, Laravel provides a simple mechanism for caching these requests using just one method call.
Let's get all the questions from the database, but at the same time cache the request, since this table is unlikely to change often.
$questions = Question::remember(60)->get();
That's all! Now, over the next hour, this request will be stored in the cache, and the database will be untouched.
6. Template composers
You will encounter situations when several templates require some variable or piece of data. A good example of this is the navigation menu, which displays a list of tags.
To keep controllers with minimal code, Laravel offers template composers (views) to manage these things.
View::composer('layouts.nav', function($view){
$view->with('tags', ['tag1', 'tag2']);
});
Using this piece of code, at any time when the layouts / nav.blade.php file is loaded, it (the file) will have access to the $ tags variable.
7. Simple authorization
Laravel takes a very simple authorization approach. Just pass the array of data that you most likely received from the login form to Auth :: attempt (). If the provided array matches what is stored in the users table, the user will be immediately authorized.
$user = [
'email' => 'email',
'password' => 'password'
];
if (Auth::attempt($user))
{
// пользователь авторизован
}
What if I need to exit when going, for example, to the / logout URI?
Route::get('logout', function(){
Auth::logout();
return Redirect::home();
});
8. Resources
Working RESTfully at Laravel is also very easy! To declare a controller a resource, simply call Route :: resource () as follows.
Route::resource('orders', 'OrdersController');
This code will register 8 routes.
- GET / orders
- GET / orders /: order
- GET / orders / create
- GET / orders /: order / edit
- POST / orders
- PUT / orders /: order
- PATCH / orders /: order
- DELETE / orders /: order
Further, OrdersController can be generated from the command line:
php artisan controller:make OrdersControllerIn this controller, each method will correspond to one of the routes described above. For example, / orders will call the index method, / orders / create - the create method and so on.
Now we have the necessary strength to easily build RESTful applications and APIs.
9. Template Blade
Yes, PHP is a template language by nature, but it hasn't become too good. However, it's okay. Laravel offers its Blade engine to fill the gap. Just name your templates with the extension .blade.php and they will be parsed accordingly. Now we can do the following:
@if ($orders->count())
<ul>
@foreach($orders as $order)
<li>{{ $order->title }}</li>
@endforeach
</ul>
@endif10. Testing Tools
Since Laravel uses Composer, we immediately have PHPUnit support out of the box. Install the framework and run phpunit from the command line to test.
In addition to this, Laravel offers a number of helpers for some common types of functional tests.
Let's check that the home page returns a 200 response code.
publicfunctiontest_home_page(){
$this->call('GET', '/');
$this->assertResponseOk();
}
Or maybe we want to check that when the contact form is sent to the server, the user is redirected to the home page with the message.
publicfunctiontest_contact_page_redirects_user_to_home_page(){
$postData = [
'name' => 'Joe Example',
'email' => 'email-address',
'message' => 'I love your website'
];
$this->call('POST', '/contact', $postData);
$this->assertRedirectedToRoute('home', null, ['flash_message']);
}
11. Component “Remote control”
Part of Laravel 4.1, which was released in November 2013, was the ability to write a console command for Artisan to connect to the server via SSH and perform any actions. Just use the SSH facade:
SSH::into('production')->run([
'cd /var/www',
'git pull origin master'
]);
Pass an array of commands to the run () method, and Laravel will do the rest! Now, since it makes sense to execute commands as Artisan commands, you just need to execute
php artisan command:make DeployCommandand write the necessary code in the fire () method to execute the deployment.12. Events
Laravel offers an elegant implementation of the Observer pattern that you can use anywhere in your application. Subscribe to native events, such as illuminate.query, or start and listen to your own.
Thoughtful use of events will give you many opportunities.
Event::listen('user.signUp', function(){
// выполните то, что надо,// когда пользователь регистрируется
});
Like most things in Laravel, if you prefer to specify a class name rather than an anonymous function, you can safely do it. Laravel will ruin everything using an IoC container.
Event::listen('user.signUp', 'UserEventHandler');
13. Show routes

The application is growing, and it can become hard to see which routes are described. Especially if you did not pay enough attention to the routes.php file (for example, excessive description of routes).
Laravel offers a convenient routes command that will show all registered routes, along with the controller methods that these routes call.
php artisan routes
14. Queues
Think about an event when a user logs into your application. Most likely, a number of side events will occur. The database should be updated, the score should increase, a welcome letter should be sent, and so on. Unfortunately, such actions tend to be time consuming.
Why make users wait for these events to happen if we can send these events to run in the background?
Queue::push('SignUpService', compact('user'));
Perhaps the most remarkable thing is that Laravel works great with Iron.io “push” queues. This means that even without experience with workers or demons, we can still use queues. Just describe the route using the php artisan queue: subscribe command, and Iron.io will send data to this URL every time a task is queued. And this route, in turn, will perform the necessary actions.

15. Simple validation
When validation is needed, Laravel comes to our aid again! Using the Validator class is easy. Just pass the object for validation along with the rules to the make method, and Laravel will do the rest.
$order = [
'title' => 'Wii U',
'description' => 'Game console from Nintendo'
];
$rules = [
'title' => 'required',
'description' => 'required'
];
$validator = Validator::make($order, $rules);
if ($validator->fails())
{
var_dump($validator->messages()); // validation errors array
}
16. Tinker

Especially if you are using Laravel for the first time, it may be useful to tinker with the kernel. The tinker team will help with this.
Tinker uses the popular component Boris.
$ php artisan tinker> $order = Order::find(1);
> var_dump($order->toArray());
> array(...)
17. Migration
Think of migrations as version control of a database. At any time, you can “roll back” migrations, return them, update, and so on. Probably, the power of migrations lies in launching the application into production and simply running the php artisan migrate command to construct the database.
To prepare the schema for the new users table, we can execute:
php artisan migrate:make create_users_tableThe command will generate a migration file, which you fill in as you need. As you are ready, the php artisan migrate command will create the table. That's all! Need to roll back the changes? Easy! php artisan migrate: rollback.
Here is an example table for the FAQ table.
publicfunctionup(){
Schema::create('faqs', function(Blueprint $table){
$table->integer('id', true);
$table->text('question');
$table->text('answer');
$table->timestamps();
});
}
publicfunctiondown(){
Schema::drop('faqs');
}
Note that the drop () method does the opposite of the up () method. This is what allows you to “roll back” migration. Isn't that a lot easier than tormenting with pure SQL?
18. Generators
Laravel offers a number of generators. But there is also a package called “Laravel 4 Generators”, and it went even further. It can generate resources, files for filling the base, pivot tables and migrations.
In the previous paragraph, we were forced to write the scheme ourselves. But using the generator package, we can execute the command:
php artisan generate:migration create_users_table --fields="username:string, password:string"And the generator will do the rest. With this command you can prepare and create a new table in the database.
Laravel 4 Generators can be installed through Composer.
19. Console teams
A number of cases have already been described when it will be useful to write custom commands. They can be used in building applications, file generation, deploy applications and everything else.
Since this is a common task, Laravel makes the process of creating commands the easiest.
php artisan command:make MyCustomCommandThis command will generate the desired template for your custom team. Next, in the newly created file app / commands / MyCustomCommand.php, fill in the name and description.
protected $name = 'command:name';
protected $description = 'Command description.';
And, in the fire () method, perform the necessary actions. After that, it remains only to register the command for Artisan, in the file app / start / artisan.php.
Artisan::add(new MyCustomCommand);
Believe it or not, but that's it! Now you can call this command from the terminal.
20. Test the facades
Laravel makes a lot of use of the Facade template. This makes it possible to use the “static” syntax, which, no doubt, you will like (Route :: get (), Config :: get (), and so on), and at the same time allows you to fully test them.
Since the “underlying” class is resolved through the IoC container, we can easily replace the “lower” classes with our test ones. This allows us to do the following:
Validator::shouldReceive('make')->once();
Yes, we call shouldReceive directly from the facade. “Behind the scenes,” Laravel uses the Mockery framework. This means that you can absolutely use the facades, and at the same time test absolutely all pieces of code.
21. Form helpers
Since building forms is often a cumbersome task, the Laravel form builder steps in to facilitate this process, as well as use some of the “style features” associated with form design. Here are some examples:
{{ Form::open() }}
{{ Form::text('name') }}
{{ Form::textarea('bio') }}
{{ Form::selectYear('dob', date('Y') - 80, date('Y')) }}
{{ Form::close() }}
What about the task of remembering the entered data during the last form submission? Laravel does it automatically!
22. IoC container (Inverse of control)
At the core of Laravel is a powerful IoC container, which is a tool to help manage class dependencies. It is worth noting that he has the power to automatically determine the necessary classes without presets.
Just typehint your dependencies in the constructor, and upon initializing Laravel using the PHP Reflection API, it will correctly read your prompts and try to insert these classes for you.
publicfunction__construct(MyDependency $thing){
$this->thing = $thing;
}
When you request a class from an IoC container, dependency resolution will happen automatically.
$myClass = App::make('MyClass');
It is important to note that controllers are always requested from the IoC container. Therefore, you can freely typehint for the dependencies of your controllers, and Laravel will try to implement them.
23. Environment
One environment may be suitable for small projects. For other projects, multiple environments are vital! Development, testing, production. All this is vital and each environment requires its own settings.
Perhaps your test environment uses an in-memory database for testing. Maybe your dev environment uses other API keys. And the production environment uses its database connection settings.
Fortunately, Laravel makes our work easier again. Take a look at bootstrap / start.php.
There is a simple demonstration of setting up the local environment, which is based on the hostname of the computer.
$env = $app->detectEnvironment(array(
'local' => array('your-machine-name'),
));
In general, this will work. But it is preferable to use environment variables for such things. Don’t worry, this is easy to do in Laravel! Just pass the function to the detectEnvironment method.
$env = $app->detectEnvironment(function(){
return getenv('ENV_NAME') ?: 'local';
});
Now, if the environment variable is not set (and you set it for production), the environment will be local.
24. Easy setup
Laravel again uses a very simple configuration approach. Create a folder with the name of the environment in the app / config folder, and any configuration files in this folder will take precedence over others, provided that you are in this environment. For example, you can specify a different API key for the dev environment.
<?php// app/config/development/billing.phpreturn [
'api_key' => 'your-development-mode-api-key'
];
The configuration is fully automatic. Just call the method
Config::get(‘billing.api_key’)and Laravel will determine from which file to read this value.25. Learning
When it comes to learning, the Laravel community is infinitely good, despite being young. For a little over a year, half a dozen different books have been published related to Laravel development.