Laravel is a popular open-source PHP framework that’s known for its robust security and simple yet sophisticated coding architecture. It’s a great choice for building cutting-edge web applications capable of driving revenue and propelling businesses forward.
No PHP developer is untouched by Laravel these days. They’re either a junior or mid-level developer who loves the rapid development Laravel offers, or they’re a senior developer who is being forced to learn Laravel because of market pressures.
With over a million websites powered by Laravel, Google pushes the importance of website speed, and users are less & less accepting of anything other than an incredibly smooth user experience – some are giving PHP & frameworks like Laravel the reputation of being less performant than other frameworks. While there very well may be truth to this, that doesn’t mean there isn’t anything you can do about it – so, in this guide, we’ll dive deep into how you can optimize Laravel for performance.
Today, Laravel has become a very popular framework for developing business and E-Commerce applications. Most organizations prefer Laravel to build their business applications. There are numerous reasons for that. But today we will only focus on performance optimization.
Why Is Laravel Performance Optimization So Important?
This article will go over several important tips, each with step-by-step guides to optimize your Laravel website. While some of the steps may sound technical, the steps will be easy to follow and recreate on your own screen.
1. Route Caching
Laravel allows you to cache the routes. You can execute the Artisan command:
php artisan route:cache
and all your routes would then be cached in the routes.php file.
Next time when the routes are required, the cache would be accessed instead of the routes file. This increases your site performance by routing the requests in a speedy manner.
To clear the cache, you use a similar command:
php artisan route:clear
Route caching is a simple way to make your website feel snappier and load faster.
2. Use Artisan Commands Effectively
One of the best features of Laravel is its command-line tool called Artisan. If you use it effectively, you can boost your application’s performance.
You can cache the routes as well as the config. You can execute the below command to cache config and routes:
php artisan config:cache
php artisan route:cache
Note: Artisan Optimize was removed in laravel 5.5 this works in previous versions.
php artisan optimize --force
Do remember to clear the cache, when you are adding new config or new routes. You can use the below command to effectively clear the cache.
php artisan config:clear
php artisan route:cache
php artisan view:clear
3. Config Caching
Laravel provides an exceptionally interesting command, Artisan Cache Config that is very helpful in boosting performance. The basic usage of the command is:
php artisan config:cache
Once you cache the config, the changes you make do not have any effect. If you wish to refresh the config, just run the above command once again. In order to clear the config cache, use the following command:
php artisan config:clear
4. Eager Loading
When you execute any query in Laravel, it will lazily execute the query. It will fetch the data only when it is required.
In some cases, this lazy loading behavior increases the number of queries executed and at the same time decreases the performance of the application.
Let us look at a simple example to understand this behavior in detail. If you want to fetch the name of the author of the books located in a library.
With lazy loading, you will end up executing N+1 queries to find your result. You can see it from the below code sample.
$books = Book::all();
foreach ($books as $book) {
echo $book->author->name;
}
In the below code, every time the for loop executes, the query gets executed. To solve this problem, Laravel allows you to eagerly load the data.
This enhances your query execution time and decreases the number of queries. The below code sample shows how we can easily load the complete list in just a query.
$books = Book::with('author')->get();
foreach ($books as $book) {
echo $book->author->name;
}
5. Optimize Composer
Laravel uses a separate tool called Composer to manage different dependencies. When you initially install Composer, it loads dev dependencies into your system by default.
These dependencies are useful for developing a website. But once your site is fully operational, they’re no longer required, and in fact, they’ll only slow it down.
When utilizing Composer to install packages, use the --no-dev and -o parameters as follows to remove dev dependencies:
composer install --prefer-dist --no-dev -o
This command allows Composer to create a directory for optimizing the autoloader and boosting performance. It simply requests the official distribution to be retrieved and packaged, with no dev dependencies.
Be careful not to eliminate any runtime dependencies. This could jeopardize your website's performance or even cause it to crash.
6. Minifying and Bundling Assets
Laravel mix can help you here, it compiles all your CSS and provides a single app.css file, thus reducing multiple HTTP requests to single.
you can also remove unused CSS from your project by using laravel-mix-purgecss package, just install it in your development project:
npm install laravel-mix-purgecss --save-dev
or
yarn add laravel-mix-purgecss --dev
now in your webpack.mix.js
const mix = require('laravel-mix');
require('laravel-mix-purgecss');
mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css')
.purgeCss();
7. Queues
Laravel queues work like your CPU. Whenever your computer processes a task, it does so in the most efficient way possible that doesn’t degrade the quality of the user’s experience. This means that when you’re rendering a file or doing something resource intensive, your CPU makes sure that you still have processing power left for your other tasks until its limit is reached.
As an example, when a user registers to the website, then we have to perform many actions in the backend like store user information, send activation mail, send welcome mail, etc. If we simply send a mail (without queues) then it will take around 4-5 seconds. And the user has to wait until the request. So, with queues, we just need to push actions inside the Queues after performing required validations and showing a user success message. After that, we just need to handle basic things when queues will execute.
Simple examples of this are:
- Sending emails
- Downloading files
- Uploading files
These tasks don’t need to be seen by the user and can be done as a background process.
Laravel also has several queue driver support documentations and offers unique solutions for each, such as Horizon, a dashboard that monitors your queue system.
8. Fast Cache or Session Drivers
To improve the performance of Laravel applications, we can store sessions and cache them in RAM. Memcached is the best and fastest cache and session driver for this. Laravel is flexible to switch one cache/session drive to another.
For the session driver, we can change the driver key in config/session.php and for cache, we can change the driver key in the config/cache.php file.
9. Database Indexing
When we are talking about increasing the performance of the application, we are following many practices in Laravel like caching, data loading, asset minification, etc. But there is one more thing, which can help us to improve performance, i.e. database indexing. This is basically a database-level technique.
Basically, database indexing is data structuring that is based on one or more columns of the database table. The main idea behind indexing is to speed up data retrieval. It helps in locating the data easily without needing to go through each and every row, every time the database is accessed.
Using columns, indexing helps in minimizing the disk accesses for each query that is processed. Making database indexing a powerful technique for database optimization also improves the overall database performance.
In Laravel, we can create indexing by the use of migrations. Below is the example:
Schema::create(‘users’, function (Blueprint $table) {
$table->string(’email’)->index();
});
10. Leverage JIT Compiler
PHP is a computer machine and server-side language. It does not comprehend PHP code natively. Usually, the programmers use a compiler to compile the code into bytecode and interpret the PHP code. The program compilation procedure affects Laravel application performance and the user experience. SO, Laravel programmers can use Zend Engine, which comes with the just-in-time compiler, to compile the code quickly and at once.
11. Compress Images
If your Laravel application contains many images, you should compress all of them to optimize the performance. There are some ways to do the optimization. However, different images require different tools to maintain the quality and resolution of images.
If you use Laravel Mix, it is advisable to use an NPM package like ImageMin while compiling your images. For a very large image, try TinyPNG to compress the image first and then use ImageMin to compress it as much as possible.
12. Views Caching
The view cache is another aspect of the application that contains a cache. The view cache stores generated Blade templates to increase the speed of your project. You can use the artisan command below to compile all views manually and optimize performance:
php artisan view:cache
Remember to clear the cache when you upload a new code; otherwise, Laravel will use your old views and you will spend lots of time trying to troubleshoot this. Run this command to clear the view cache:
php artisan view:clear
13. Remove Unused Service
You can easily inject the services using the service container framework provided by Laravel. You just need to add the name of the service in the provider's array which is present in the config/app.php file.
But at the same time, you should turn on only those services, which you are using. All other unused services should be stopped.
You can stop these services by commenting on these services in the config/app.php file. This will decrease the time your application takes to boot and increase its performance.
14. Using CDN to deliver static content
CDN is a great way to deliver static content across the globe. If your application is getting popular, you may want to add the CDN infrastructure for your application.
Let me take a simple example in which you have hosted your application on a server that is present in the US. Now if you have a request coming from India, it would take a long time for you to serve content for that request.
In order to solve this issue, CDN came into the picture. CDN caches multiple static pages. Now the request first goes to the CDN and if the content is present at the CDN, the page is directly served. This greatly enhances your content serving speed as well as the end-user experience.
15. Minify CSS & JS
You should always compress the CSS and JavaScript files before you actually bundle these files in the production environment. This will enhance your user experience as well as reduce HTTP calls. This is a great Laravel Performance Optimization tip.
There are various tools that are available to compress these files and bundle them as a single file. You can use Laravel-packer which allows you to bundle and minify your CSS and JavaScript code. You can also resize your images to generate thumbnails if required.
16. Remove Dev Dependencies
Dev dependencies are often injected into your system by default when installing Laravel or a composer for the first time. While these dependencies do aid in building your website, you don’t need these dependencies when your site is up and running.
You can input this simple command through Artisan to remove those dependencies:
composer install --prefer-dist --no-dev -o
NOTE: Dev dependencies are different from dependencies that are required at runtime. Don’t delete runtime dependencies as this may affect your website’s performance or even crash certain parts of your site.
17. Use Lumen for Small Projects
There are occasions when developing a small application (e.g. mobile or Angular apps) doesn’t demand the use of a full-stack framework like Laravel. In this scenario, consider using Lumen instead.
Lumen is a microframework developed by the same creator of Laravel. Like a lighter version of Laravel, Lumen is all about speed and performance for microservices. It requires minimal setting and alternative routing parameters when building web apps, allowing for a faster development process.
For example, Lumen can handle 100 requests per second. You can also integrate tools or packages from third parties to get new features. Moreover, Lumen supports all platforms and allows you to upgrade to Laravel.
18. Limit Included Libraries
Laravel gives you the freedom to add as many libraries as you want. While this is an awesome feature, adding a boatload of libraries puts a lot of pressure on your application’s performance. It can also affect the entire user experience.
It’s therefore vital to scan all of the libraries’ data currently in use within the code. You can find these libraries in the config/app.php file. While examining the libraries, remove the ones that you know are no longer useful to you.
It’s also a good idea to review composer.json for unneeded dependencies.
Thank you for reading this blog.
Top comments (2)
Awesome blog post - thank you, great tips there that will ensure any Laravel application is running smoothly.
Lumen is no longer recommended for new projects (info taken from official website).