Since its emergence in 2011, Laravel has become a very popular option for developing business-focused applications including information management systems (popularly known as business information management systems) and eCommerce platforms. One important aspect of this popularity is Laravel performance optimization that allows developers to finetune the performance of Laravel apps.
Why Businesses Should Focus on Laravel Performance Optimization
The structure of the framework and the associated libraries ensures that developers are able to create powerful code with minimum effort. However, the code still has room for optimization that could be used for Laravel performance tuning to ensure smooth performance after deployment.
Performance and optimization are two key factors that determine the success of every business application. In this context, ensuring the performance of the Laravel application is a crucial skill that every developer should be able to deliver to their clients. Since Laravel is often used to build business information systems, the performance of Laravel powered applications has serious implications for the success of the business. In many cases, the management information systems that provide decision making support to management layers need to be fast and high performing at all times.
Laravel Performance Optimization
In this article, I have collected several important tips for optimizing Laravel 5.5 apps performance. I believe these tips would prove to of great help to Laravel developers who are responsible for maintaining Laravel powered business apps.
For the purpose of demonstrating the ideas discussed in this article, I will use an Employee Management System in Laravel.
You Might Also Like: Install Laravel 5.8 on Server
Prerequisites
For the purpose of this tutorial, I assume that you have a Laravel application installed on a web server. My setup is:
- Laravel 5.5
- PHP 7.1
- MySQL
To make sure that that I don’t get distracted by server-level issues, I decided to use Cloudways Laravel cloud hosting because it takes care of server-level issues and has a great devstack to host Laravel project. You can try out Cloudways for free by signing for an account.
Get Maximum Web Speed With Painless Laravel Servers
Don’t Worry About the Lack of Web Performance. Our Laravel Servers Got You Covered!
You might also like: Enhanced Cloudways Staging Environment Is Now Available for All Users
Tips to Improve Laravel Performance
- Config caching
- Routes caching
- Remove Unused Service
- Classmap optimization
- Optimizing the composer autoload
- Limit Use Of Plugins
- JIT Compiler
- Choose a faster cache and session driver
- Cache the queries results
- Use “Eager Loading” of Your Data
- Precompile Assets
- Use CDN for delivering your static assets.
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
To further optimize the application, you could use OPcache that caches the PHP code so you don’t need to recompile it.
You might also like: How To Setup Laravel Application On Cloudways With Redis Cache
Routes Caching
Routes caching is an essential optimization feature, particularly for apps with a lot of routes and configurations. 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
You might also like: An Introduction To Routing In Laravel
Remove Unused Service
In the context of Laravel performance tuning, an important tip is not to load all services through the config. While you are there, always remember to disable unused services in the config files. Add comments to these service providers.
Classmap Optimization
Even a mid-level Laravel app has a number of files because Laravel has the habit of calling including 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 scan the application and create a one-to-one association of the classes and files in the application. Use the following command:
composer dumpautoload -o
Limit Included Libraries
The good thing about Laravel is the 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’ tata recalled 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. Another important place to look is 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.
Choose a Fast Cache and Session driver
For optimal Laravel performance tuning, the best route is to store the cache and session sections in the RAM. I believe the fastest cache and session drivers for Laravel 5 performance 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
You might also like: Using Memcached With PHP
Cache Queries Results
Caching the results of the queries that are frequently run is a great way of improving Laravel 5.5 performance. For this, I recommend the remember function, that is used as follows:
$posts = Cache::remember('index.posts', 30, function() {return Post::with('comments', 'tags', 'author', 'seo')->whereHidden(0)->get();});
Use “Eager Loading” for Data
Laravel offers a great ORM for dealing with databases. Known as Eloquent, it creates models that abstract the database tables from the developers. Using simple structures, developers could use Eloquent to deal with all CRUD operations in PHP. 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:
$books = AppBook::all(); foreach ($books as $book) { echo $book->author->name;}
In contrast, eager loading query will look like:
$books = AppBook::with('author')->get(); foreach ($books as $book) { echo $book->author->name; }
You Might Also Like: Improve MySQL Performance With This Guide
Precompile Assets
For Laravel application tuning, developers often distribute code into separate files. While this keeps the code clean and manageable, it does not contribute to efficient 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 Delivering 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 CloudwaysCDN area. This outcome is a fundamentally quick page stack speed and an incredible affair for the client. CloudwaysCDN is a benefit based CDN. This implies you have to characterize the static resources (JS, CSS, HTML, pictures, recordings, and liveliness, and so forth.) on a specific application.
Assets Bundling
Laravel Mix comes by default with all Laravel applications. Using 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, I will use Laravel Mix for the compilation. With that practice, we can efficiently concatenate several stylesheets into a single file.
mix.styles([ 'public/css/vendor/normalize.css', 'public/css/styles.css' ], 'public/css/all.css');
It will create all.css containing styles from normalize.css and styles.css. This way, we can use all.css in our HTML easily, instead of including both normalize.css and styles.css individually. This will, in turn, reduce the number of HTTP requests needed to retrieve these files individually. Because now it requires just one request instead of two to retrieve a file. And as a result, we notice a slight increase in the speed of our application.
Assets minifying
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.
Running the latest version of PHP
The latest version of PHP has brought significant improvements in its performance. Therefore ensure that your Laravel application is running the latest version of PHP so that you can tap all the performance improvements introduced in the new version in your application.
Cloudways also has PHP7.2 integrated by default in its platform. So that users can optimize their apps with flawless speed and performance using the advanced functionalities of the platform.
The platform gives you the ease to change your previous PHP versions to the newer PHP7.2 within a click.
Laravel Debugbar
Though not an optimization technique, but a package. Laravel Debugbar is a package to integrate PHP Debug Bar with Laravel 5. 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.
You Might Also Like: How to Use Composer in Laravel 5.5
General Performance Tuning Tips for Laravel
Laravel is often used to create websites and web portals. In many cases, optimizing the performance of the website is just a matter of implementing several tweaks, such as:
- Laravel page speed composer package
- Update provider details
- Publish the package
- Register your Middleware
- Make route over a page
- Create Blade File
- Run app
Laravel page speed composer package
Download and extract renatomarinho/laravel-page-speed package using Composer. Simply add the package name with version details in a composer.json file and run a composer update command:
"require": { ...... ...... "renatomarinho/laravel-page-speed": "^1.8" },
Next, run the following command:
composer update
Update Provider Details
After successfully extract the package, Go to config/app.php file and append service provider and alias details with specific classes.
'providers' => [ .... .... RenatoMarinhoLaravelPageSpeedServiceProvider::class, ],
Publish the package
After adding provider details we need to publish the particular package to implement in our application. Following command help us to publish the package after executing the command only we can use the package
php artisan vendor:publish --provider="RenatoMarinhoLaravelPageSpeedServiceProvider"
Adding middleware for web access
After publishing the package we need to add middleware details in the Kernel.php file. Just copy and paste it following codes under $middlewareGroups,
protected $middlewareGroups = [ 'web' => [ ........ ........ RenatoMarinhoLaravelPageSpeedMiddlewareInlineCss::class, RenatoMarinhoLaravelPageSpeedMiddlewareElideAttributes::class, RenatoMarinhoLaravelPageSpeedMiddlewareInsertDNSPrefetch::class, RenatoMarinhoLaravelPageSpeedMiddlewareRemoveComments::class, RenatoMarinhoLaravelPageSpeedMiddlewareTrimUrls::class, RenatoMarinhoLaravelPageSpeedMiddlewareRemoveQuotes::class, RenatoMarinhoLaravelPageSpeedMiddlewareCollapseWhitespace::class, ] ] Define Route I going to add a route to check Optimized Website Speed and Performance in Laravel 5.5 Route::get('/listView', function () { return view('listView'); });
View page details
In final, create a blade file and include a set of our code to display.
How Our Custom Stack Boost Performance
Known as ThunderStack, our custom stack is designed to boost the performance of Laravel apps. The winning recipe comprises of Apache and NGINX, Varnish and Memcached. On the database side, you have the choice of either MySQL or MariaDB. In addition, you could enable Redis as a session driver or could configure Varnish according to project needs.
You might also like: Laravel 5 Performance Benchmarks For PHP 7.0, 7.1 And 7.2 on Cloudways
Redis
[–]DKRY [+1]
Redis caching, dedicated server or vps to keep application code in RAM. CDN for static files. Use queues for tasks that take more than a few seconds or task that does not need to be synchronous.
from proyb2
I came here to share 2 things, optimize with SPA and use static pages, these improve user experience is a lot important.
Hoang LeHoang .
Backend: Reduce db query and use cache Frontend: Combine and minify js/css, use lossless method to compress images
Frequently Asked Questions
Q: How can Redis help improve Laravel’s performance?
A: Redis can be utilized for cache and sessions to provide more control over performance. It is an in-memory data structure store that can be applied as a database and cache, or even as a message broker.
Q: How to test Laravel Website Performance?
A: There are several website performance testing tools which you can choose as per your preference;
- Pingdom
- GTmetrix
- Google PageSpeed Insights
- WebPageTest
- Varvy
- Uptrends
Q: What are the different types of PHP based website optimizations?
A: PHP websites can be optimized on the following 4 possible levels;
- Language-level: This means you use a faster/latest version of the language to avoid specific styles of coding in the language that makes your code slow.
- Framework-level: These factors are covered in this article.
- Infrastructure-level: Tuning your PHP process manager, web server, database, etc.
- Hardware-level: Moving to a better, faster, more powerful hardware hosting provider. Try Cloudways.
Q: Which tool to use for Minifying and Bundling Assets?
A: Laravel Mix is an effective tool to define Webpack builds for PHP applications. It concatenates multiple assets like CSS into a single filing and reduces multiple HTTP requests to single, which helps towards our goal of Laravel Performance Optimization
Q: How many requests can Laravel handle?
A: Without Sessions:
Laravel: 609.03 requests per second (mean)
Zend: 559.91 requests per second (mean)
With Sessions:
Laravel: 521.64 requests per second (mean)
Zend: 484.94 requests per second (mean)
Conclusion
Laravel performance tuning and optimization is an essential concern for all businesses that rely upon Laravel powered tools for business processes. By implementing the above-mentioned tips, Laravel developers who create and maintain business applications could ensure speed and reliability for the business.
Launch Laravel apps with 1-Click Install. Painless Server Management
Deploy your apps on optimized Laravel hosting servers.
Pardeep Kumar
Pardeep is a PHP Community Manager at Cloudways – A Managed PHP Hosting Platform. He love to work on Open source platform , Frameworks and working on new ideas. You can email him at [email protected]
Keep reading the article at The Official Cloudways Blog. The article was originally written by Pardeep Kumar on 2020-07-12 04:14:48.
The article was hand-picked and curated for you by the Editorial Team of WP Archives.