Top 15 tips and tricks to Optimize Laravel Performance

Ahmad W Khan
6 min readOct 2, 2020

--

Laravel is a great back-end framework for server side logic implementation. It has intuitive code structure, great documentation and very active community. Although the learning curve for Laravel is a bit steep, the payoff is also great. Laravel provides out of the box security tools for the application. With all that being said, while I was building my REST API using Laravel, I found the performance starting to slow down as the APIs grew larger.

So, I thought I’d do a post on how to optimize a Laravel back end system for maximum performance. In larger projects, performance is a key deciding factor in determining the success of the product. So, ensuring the performance of the Laravel application and optimizing the application down to the code level is a crucial skill that every developer should have. Since Laravel is used to build business products most often, the performance of Laravel powered applications has serious implications for the success of the business.

Here are the top 15 tips and tools to Optimize Laravel Performance:

Let’s start off with some of the tools that are absolutely vital for your Laravel Application:

Laravel Telescope

Laravel Telescope is an elegant debug assistant for the Laravel framework. Telescope provides insight into the requests coming into your application, exceptions, log entries, database queries, queued jobs, mail, notifications, cache operations, scheduled tasks, variable dumps and more. Telescope is a must have monitoring and analysis tool for any apis built using Laravel.

Laravel Debugbar

Laravel Debugbar is a package to integrate PHP Debug Bar with Laravel. It includes a ServiceProvider to register the debugbar and attach it to the output. It is a package that can be used as a Laravel performance monitor. It is recommended to make use of this package while developing your application. Because with it, you can easily inspect how your application is running, and then improve accordingly.

Now, let’s move onto actual tips to tune the performance of your Laravel Application

Config Caching:

Let’s start with basic caching first. Laravel provides a cool 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

Also, you could use OPcache that caches the PHP code so you don’t need to recompile it.

Routes Caching

Applications with a lot of routes and configurations, routes caching is an essential optimization feature. The routes cache is a simple array and helps in speeding up Laravel performance because of the faster loading of the array. For this, run the following command:

$ php artisan route:cache

Remember to run the command every time config or the routes files have been changed. Otherwise, Laravel will load old changes and from the cache. For clearing the cache, use the following command:

$ php artisan route:clear

Declutter the app from unnecessary services

To further improve the performance of a Laravel app, load all services through the config. Also, always remember to disable unused services in the config files.

Classmap Optimization

Laravel tends to have a fairly large number of files because Laravel has the habit of calling multiple files for include requests. A simple trick is to declare all the files that would be included, to include requests, and combine them in a single file. Thus, for all include requests, a single file will be called and loaded. For this, use the following command:

$ php artisan optimize --force

Composer Optimize Autoload

It is a good idea to use Composer to scan the application and create a one-to-one association of the classes and files in the application. Use the following command:

$ composer dump autoload -o

Reduce Redundant Dependencies

Laravel comes with a huge number of libraries that could be included in an app. While this is a good thing, the downside is the high level of drag that the application experiences and the overall experience slow down. This is why it is important to review all the libraries that are called within the code. If you think you could do without a library, remove it from the config/app.php to speed up the Laravel app. Also look for any unused dependency in composer.json.

JIT Compiler

Translating PHP code to bytecode and then executing it is a resource-intensive process. This is why go-between such as Zend Engine is required to execute the C subroutines. This process has to be repeated every time the app is executed. To reduce time, it is essential that this process is repeated just once. This is where the Just-in-Time (JIT) compilers prove to be very useful. For Laravel apps, the recommended JIT compiler is HHVM by Facebook.

Cache and Session driver

For optimal Laravel performance tuning, the best route is to store the cache and session sections in the RAM. My recommendation is Memcached. The driver key for changing the session driver is usually located in app/config/session.php. Likewise, the driver key for changing the cache driver is located in app/config/cache.php

Cache Queries Results

Caching the results of the queries that are frequently run is a great way of improving Laravel’s performance. For this, I recommend the remember function, which is used as follows:

$articles=Cache::remember(’index.articles’, 30, function()

{

return Article::with('comments', 'tags', 'author', 'seo')->whereHidden(0)->get();});

}

Use “Eager Loading”

Laravel uses an ORM called Eloquent which creates models that abstract the database tables from the developers. When Eloquent uses eager loading, it retrieves all associated object models in response to the initial query. This adds to the response of the application. Let’s compare lazy loading and eager loading:

The lazy loading query will look like:

$posts = App\Post::all(); foreach ($posts as $post)

{

echo $post->author->name;

}

In contrast, eager loading query will look like:

$posts = App\Post::with(’author’)->get();

foreach ($posts as $post) {

echo $post->author->name;

}

Precompile Assets

It’s a common practice for developers to distribute code into separate files. While this keeps the code clean and manageable, it is not very efficient in production. To help developers in this context, Laravel provides a simple command:

$ php artisan optimize

$ php artisan config:cache

$ php artisan route:cache

Use CDN for Static Assets

Loading static assets files from the CDN server (as opposed to loading it directly from the server that hosts the files) will improve Laravel application performance. Once a client visits a site, some portion of the information is served from the closest CDN area. This outcome is a fundamentally quick page stack speed and an incredible User Experience.

Assets Bundling and Minifying

Laravel Mix is a tool that uses several common CSS and JavaScript preprocessors, Laravel Mix provides an effective API to define Webpack build for your PHP applications. To compile application assets including script, styles, and others. We can efficiently concatenate several stylesheets into a single file.

Compiling all assets in a single place might end up with a huge size file. As a result, this practice will not allow our application to benefit from the proposed compilation. Therefore to resolve this issue, we can minify our assets using Laravel Mix.

$ npm run production

This will run all Mix tasks and make sure our assets are production-ready by minifying them. Once minified, the assets will become smaller in size, hence will be retrieved faster, which will speed up the performance of our application.

Conclusion

That’s it for this post. I hope you found some of the tips helpful. By implementing the above-mentioned tips, Laravel developers who work in the backend to create and maintain business applications could make sure that the software they are building runs fast and is optimized for performance.

Original post: https://blog.ahmadwkhan.com/top-15-tips-and-tricks-to-optimize-laravel-performance

--

--