Streamline PHP Development Through These Laravel Best Practices

by Saquib Rizwan  June 20, 2017

Laravel is a modern PHP development framework that provides a whole host of features and third party solutions required for building modern, maintainable, real-time, distributed web applications. Given all this, Laravel is rapidly becoming popular after the release of PHP7 because of high performance benchmarks.

Laravel Best Practices

This article aims to highlight the best practices of Laravel development which are essential for streamlining the development process and ensuring high quality of the final product.

Use The Latest Stable Version

Although the release of Laravel 5.5 is just around the corner, the recommended best practice is to always use the latest stable version for the development of your application. At the moment, Laravel 5.4 is the latest stable version available.

Follow the Standards

Every framework has its own internal code development standards. The good thing is that Laravel does not restrict you to these standards as long as your variables are compatible with the composer. However, experts recommend that you should follow the PSR-2 and PSR-4 coding standards.

Artisan Command Line Interface

Laravel has its own command line interface known as Artisan. It uses the Symfony Console component as its foundation. It provides various helpful commands to speed up the application development process. Here the best practice is to always use Artisan CLI as it increases the productivity of the development process.

Artisan commands are also helpful in task scheduling task and triggering action(s) on the occurrence of an event. For example, you can fire an Artisan command from an HTTP route by using Artisan facade:

Following are several helpful Artisan commands that speed up the Laravel application development process:

php artisan config:cache

This command cache the config of bootstrap loading phase.It helps in limiting IO request. It needs to be re-run every time you change or add anything in the config directory. This command is  usually helpful if you have a lot of config files or packages.

php artisan route:cache

This command does the same thing but for the routes. It helps reduce the time required for the computation of routes. This command needs to be rerun after you change any routes. Also, keep in mind that you cannot use this command if you have any closure based routes.

php artisan optimize

This command optimizes the autoloader and compiles all your views

Debugging

Laravel does comes with it’s own debugging component. However, it’s a good practice to use debugging packages like Laravel Debugbar as they provide you tons of good information for optimizing your application by including a ServiceProvider to register the debugbar and attach it to the output .

You can also use testing and debugging tool like Laravel Dusk, a browser automation testing tool perfect for browser testing applications and API. It uses ChromeDriver by default but you can use any Selenium compatible drivers.

Dependency Management

Laravel is built on the various framework packages and libraries. By default. these packages are available within the Composer libraries. The best practice, in this case, is to create your own Composer library for each application specific set of classes by going through the following steps:

  1. Put your library on GitHub.
  2. Give your library a composer.json file
  3. Registration with Packagist

You can easily add custom libraries in the package which will be helpful in optimizing your application.

Eloquent ORM

The Eloquent ORM is a Laravel feature that provides elegant ActiveRecord implementation for working with your database. The best practice for working properly with the Eloquent ORM is to take care of the naming convention of your model.

In the Eloquent ORM, each database table has a model. These models are used to interact with the database and perform various operations. It works on a principle that, for a table named users, Laravel expects a model with the name User.  It is very important that you follow this convention to avoid Eloquent related problems.

Example
Consider a model with the name Products.php

The Eloquent Model uses the plural name of the class as the table name. Therefore, the table name will be products. Eloquent also expects created_at and updated_at column exists in the table. If you want to handle it yourself, set $timestamps property to false.

Use Of Autoload

In Laravel, you can use any class or even plain PHP code, as long as it could be autoloaded.This improves the performance of the scripts by preventing PHP from checking if the file is already been loaded or not. In addition, you don’t need to include the file every time you need it in your code. PHP will let you know if it is needed when it is needed.

Use Of Migrations

Laravel Migrations is a wonderful feature which provides version controlling for your database. It allows your team to easily modify and share the application’s database schema. Migrations are typically paired with Laravel’s schema builder to easily build your application’s database schema.

Always use Laravel Migrations to create database(s) rather than doing it manually. This will reduce your workload considerably.

Avoid Accessors, Mutators & Query Scopes

The performance of any Laravel application depends more on the code then the engine. It is important to avoid the dynamic nature of code when possible in order to optimize the performance of the compiler.

For example, consider the dynamic types

Accessors, mutators and query scopes do a lot of dynamic stuff that can fool the compiler and prevent it from being optimized. The more dynamic the code is, the slower it will run.

Storing Relationships in Variables

Try to reduce the relationship calls as much as possible.

Suppose that $user->posts; is called five times in the code. This will result in a massive number of unnecessary database calls, and consequently will slow down your application. The right way to deal with it is to store the result of this call in a variable such as $posts = $user->posts; and then use $posts in the code.

Keep Your Route Clean

Always make sure not to overcrowd your route.php file. Avoid writing closures in your route.php file. Instead, create a separate controller for it.

Choose The Right Database

Eloquent supports multiple databases, and thus there is no need to limit yourself to MySQL only. Use MongoDB for records that have highly variable attributes. Use ElasticSearch for high volume data search and indexing. Use Neo4J for applications that requires a complex relationships between models. Choosing the right database is a very important best practice that usually pays great dividends for your applications.

Configuration

The best practice is to make sure that your application key is set. This is the APP_KEY variable in your .env file. You can generate one via

php artisan key:generate

Always give your application a name. That is, instead of using the default app root namespace given by the Laravel install, set it to what the application is all about. This can be set via

php artisan app:name YourAppName

This makes your controllers/models etc resolve into YourAppName\Controllers and YourAppName\Models.

To know more about the Laravel best practices used by the developers, I went to Reddit and ask developers about their ideas on the topic. Here is what I got:

Avoid N+1 queries

This is when you query for relations inside of a loop (something like the following):

If you didn’t load the author relation when you queried for comments, you’ll end up making N queries for each comment’s author. You’d solve this by doing this first:

Take Care of Eloquent Relation Caching

Consider the following example:

If you were to do this (make several calls to the author relation in the same page request)

It will actually query the author once, rather than 4 times. Because once it queries the relation, it will stores it in the cache for that request and use it whenever it will be called.
However, if you do this:

Then there will be 4 separate queries, even though they were all called with the same argument. Every time you call comments() relation method like a function rather than a property, you’re generating a new query. This costs your application a whole lot of performance overheads.

Conclusion

I have listed the best practices for Laravel application development according to my experience. These practices will make your application faster and better optimized. if I have left any best practice out, you are most welcomed to add it below in the comment box.

Create Laravel apps without the worry of server management.

Deploy your app on optimized PHP hosting servers for Laravel.

About Saquib Rizwan

Saquib is a PHP Community Expert at Cloudways - A Managed PHP Hosting Cloud Platform. He is well versed in PHP and regularly contributes to open source projects. For fun, he enjoys gaming, movies and hanging out with friends. You can email him at saquib.rizwan@cloudways.com

Stay Connected:

You Might Also Like...