Quick Summary:
With rising popularity of Laravel, organizations prefer to use it for wide range of IT development projects. However, one needs to optimize the Laravel to get the best out of it. Here in this blog, we had included all possible Laravel Performance Optimization tips and tricks that will not only improve Laravel website speed but also helps you save big bucks.
Laravel has gained popularity since its origin in 2011 and has managed to secure its position as one of the best PHP framework amongst developers due to its robust features. Laravel is an open-source web application framework with a syntax that is both expressive and elegant. It comes with several useful features, like comprehensive dependency injection, an expressive database abstraction layer, queues & scheduled jobs, unit & integration testing, and more.
459,818 is the total number of live websites built on Laravel in the market.
8% of market share is aquired by Laravel among all Web frameworks technologies.
According to Google trends, Laravel has remained the most popular PHP framework for few years.
Due to the freedom it offers, developers often create applications that aren’t up to par in terms of performance. Let’s understand how much importance does performance contributes to the overall user experience.
Importance of Website Speed
Users have high expectations of their websites, and you can’t afford to let them down. In terms of improving audience engagement, income, and customer loyalty, your website’s performance is important to your success. Customer satisfaction is measured in seconds. Let’s look at a few statistics to help comprehend it better. According to Akamai –
1-second delay in mobile load times can impact conversion rates by up to 20%.
53% of people will leave a mobile page if it takes longer than 3 seconds to load.
52% of consumers expect your website page to load in two seconds or less .
4+ seconds delay in loading saw 3/4 of their web users never returning back to the site.
It might be complicated and expensive if you fail to meet user expectations. Dissatisfied customers will be hesitant to participate, lose faith in the company, and tell others about their dissatisfaction.
How to check Laravel Website Performance?
When you plan to build your Laravel application, you need to be sure it loads fast and it can be only known when you check its speed. Laravel developers make use of performance testing tools like Pingdom to measure the loading speed of the site. In most of the cases, the developers give more importance to UI and UX of the website and page load speed takes the back seat. However, page load speed is very crucial when it comes to reducing the bouncing rate and boosting SEO rankings. This means it is important that you check the speed of your website as well as carry out regular check-ups to keep it optimized using such tools.
There are many website performance testing tool from which you can choose according to your preference. Some of them are
Before diving into Laravel performance optimization, it’s important to understand PHP optimization. Below are the points in which you can optimize your PHP
Types of PHP based website optimization to Speed-Up Laravel Website.
There are 4 stages at which a php website can be optimized.
- Language-Level: This suggests you’re using a faster/latest version of the language to avoid certain coding patterns in the language that slow down your code.
- Framework-Level: This topic will be covered in this article
- Infrastructure-Level: Tuning the PHP process manager, web server, and database, among other things.
- Hardware-Level: Moving to a new hardware hosting provider that is better, quicker, and more powerful.
Tips to Improve Laravel Performance
Let’s have a look at some of the options useful for improving the performance of your Laravel Website. It contains the following items:
Use The Latest Version of Laravel
Always go with the most recent version of the PHP framework you’re utilizing to build your app or website. If you’re already using Laravel, update your framework to the most recent version to observe performance benefits. With each new version of PHP that comes out, performance and speed are improved. But keep in mind it’s not as easy as it seems, you need to audit your code and make sure you can easily and safely update to the latest version of PHP.
Use Appropriate Packages
For Laravel, there are various packages available. On GitHub, 338,705 repository results are accessible. With the help of such packages, you can extend the functionality of your Laravel site. However, these extra plugins will have to add to the framework’s burden.
Use Artisan Commands
Laravel comes with the best feature that is it’s the command-line tool called Artisan. If you use it effectively, You can boost your application performance.
You can cache the routes as well as config with using the following commands:
php artisan config:cache
php artisan route:cache
Note: Artisan Optimization was removed in Laravel 5.5. This will work for all 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
Config Caching
Cache Config is a particularly intriguing command provided by Laravel. This command is useful for improving Laravel’s performance. The command’s basic usage is as follows
php artisan config: cache
Once the configuration is configured, and you want to refresh the configuration just run the above command once again. To clear the config cache use the following command
php artisan config: clear
Routes Caching
Caching routes is a critical efficiency tool, especially for apps with a large number of routes and customizations. The routes cache is a basic array that serves to improve Laravel performance by allowing the array to load faster.
php artisan route: cache
Remember to run the program after any changes to the config or routes files. Otherwise, Laravel will use the cache to load previous updates. Use the following command to clear the cache.
php artisan route: clear
Remove Unused Service to Improve Laravel Performance
Services can be injected using the server container framework provided by Laravel. You just need to add the service in the provider array in the config/app.php
file. But keep in mind only the service that is in use should be started. Other services that are not in use can use unwanted resources and can create an unnecessary burden on the system
//AppServiceProvider.php
public function boot()
{
config(['app.timezone' => "Your time Zone"]);
config(['app.locale' => "Your Local"]);
}
//with app-settings() helper function
public function boot()
{
config(['app.timezone' => app_settings('timezone')]);
config(['app.locale' => app_settings('locale')]);
}
Optimizing Classmap Helps Boost Laravel Website Speed
Laravel applications have a huge number of files for small web applications, as it includes multiple files for each request. You can decrease the number of files by using this Laravel Optimization Trick. You can declare all the files that would be included in handling requests in a single file. Now for every request, only one file will be loaded. Use the following command to achieve this:
php artisan optimize -force
Optimizing The Composer Autoload
Laravel is designed in a way that it needs to scan the whole file system to determine the class. It’s a great help during the development process as the developer doesn’t need to change the autoloader configuration every time he adds a new file. But since the file is searched in the whole file system every time, the performance of the application goes down. You can define class-map rules
to solve this sluggishness. Because we have a map that connects the class name to its location, this dramatically increases the class loading time. Instead of scanning the entire filesystem, the file loader now only needs to check the path. You can use the command shown below.
composer dump autoload -o
Limited use of Libraries
The good thing about Laravel is it allows you to add as many libraries as you wish. But keep in mind, every new library added will create an overhead on the application. It will impact on overall experience also.
You can also review all the libraries which are currently used in your code. You can check them in the config/app.php
. While scanning this file you come across the libraries you are not currently using, you can comment on them in config/app.php
.You should also scan the composer.json to analyze all the dependencies.
Also Read: Laravel Best Practices 2021 – Let’s Stealth Your Website with Ease
Use JIT Compiler
Because PHP is not a native language, interpreters are required to transform code into bytecode that the computer can understand. Every time you run a PHP file, it is first translated to bytecode using a mediator like Zedd Engine, and then executed. This conversion will add overhead to the system, slowing down the webpage. To solve this issue you can compile the code once and use it again with JIT ( Just-in-time-compiler) to make your website responsive. The preferred JIT compiler for Laravel developers is Facebook’s HHVM.
Choose faster cache and Session driver
When you cache something in Laravel, you have a few options for where the results should be saved. Cache drivers are the name for these alternatives. So, while it’s completely fair to store cache results on a file system, that’s not what caching is for. It’s best to keep the cache and session in RAM for optimal Laravel performance tuning. You would want to utilize an in-memory cache like Redis, Memcached, MongoDB, or something similar, so that caching servers may play a crucial function rather than being a bottleneck.
Cache Query Results
One of the best-kept secrets for web application optimization is caching. For amateurs, caching means precomputing and storing the results, and sharing them when the same query is repeated. Laravel has built-in support for several types of caching. In addition to using a caching driver and building a cache system from scratch. You might want to use some Laravel packages that facilitate model caching, query caching, etc. For caching its recommended to remember the following function:
$posts = Cache::remember('index.posts', 30, function()
{
return Post::with('comments', 'tags', 'author', 'seo')->
whereHidden(0)->get();
}
);
Use EagerCoding of Data
When you execute any query in Laravel, it will lazily execute the query. In the Lazy query, it will fetch only the required data. In some cases, this will increase the number of queries executed and at the same time decrease the performance of the application. Laravel offers a great ORM called Eloquent for dealing with the database. Using simple structure, a developer can use Eloquent to deal with all CRUD operations. When Eloquent uses eager loading it retrieves all associated object models in response to the initial query. Let’s take a look at the example and understand the difference between lazy loading and eager loading.
Lazy Loading
$books = App\Book::all();<
foreach ($books as $book)
{
echo $book->author->name;}
Eager Loading
$books = App\Book::with('author')->get();
foreach ($books as $book) {
echo $book->author->name;
}
Optimizing Assets Bundle
Make sure there is a pipeline in place for any front-end assets in your Laravel application that compiles and minifies all asset files. Developers frequently distribute the code in a separate file for Laravel application optimization. While this keeps the code tidy and comprehensible, it is inefficient in terms of optimization. Laravel supports the following simple commands for optimization:
php artisan optimize
php artisan config: cache
php artisan route: cache
Another option available is Laravel Mix . It’s Laravel’s most popular feature. The mix is a lightweight wrapper over Webpack that handles production CSS, SASS, and JS. Mix.js can be this little and still do amazing things:
const mix = require('laravel-mix');
mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css');
When you execute npm run production, it will automatically take care of imports, minification, optimization, and the whole shebang. It not only works with regular JS and CSS files but also with Vue and React components in your application workflow.
“Are you looking to hire LARAVEL Developers?”
Find the best full-stack Laravel Developers in India to start your web development project within 48 hours
Mix also includes a set of APIs that you may use to create your web pack. Multiple CSS and Javascript preprocessors are supported. Laravel Mix also allows you to mix numerous CSS and JavaScript files into a single file. To merge styles, use the following code:
mix.styles
([
‘public/css/vendor/normalize.css’,
‘public/css/styles.css’
],
‘public/css/all.css’);
As we can see here, two styles normalize.css and style.css are merged in the all.css file. Now when the requests come it just has to look to the all.css file. Earlier there were two HTTP calls just to find out the style. Merging them increases the overall performance of the application.
Also Read: Laravel Security Best Practices [Ensure to Secure your Website]
Use CDN for static assets
Loading static data from CDN servers in place of loading it from the server, will improve Laravel performance. If your application is getting popular, it would be beneficial to add CDN infrastructure.
Let’s take a simple example. Suppose you have hosted your application on a server that is present in the US. Now if you have a request from India, it would take a long time to serve the content.
To solve this issue, CDN is used. CDN caches multiple static pages. Now the request first goes to the CDN, and if the content is available, the page will be directly served. This will greatly enhance content speed as well as end-user experience.
Use Queue
This suggestion may take a little longer than others, but it will be well worth it in the end. In terms of user experience, it could also be the most rewarding. Using Laravel queues is one technique to improve Laravel performance. If there is any code that isn’t required for the browser response, it can usually be queued.
Let’s look at the code to get a better understanding.
class ContactController extends Controller
{
/**
* Store a new podcast.
*
* @param Request $request
* @return JsonResponse
*/
public function save(ContactFormRequest $request)
{
$request->storeContactFormDetails();
Mail::to('[email protected]')->send(new ContactFormSubmission);
return response()->json(['success' => true]);
}
}
In the above method when the save()
method is called it will do three tasks. It stores the contact information in the database, sends an email to an address to inform them about the new contact, and returns a JSON response. The issue with this code is that the user has to wait until the user gets an email. Although it’s usually a matter of seconds yet in some cases it can cause the user to leave.
To make use of the queue system, update the code to the following
class ContactController extends Controller
{
* @param Request $request
* @return JsonResponse
public function save(ContactFormRequest $request)
{
$request->storeContactFormDetails();
dispatch(
function ()
{
Mail::to('[email protected]')->send(new ContactFormSubmission);
}
)->afterResponse();
return response()->json(['success' => true]);
}
}
The code in the save()
method above will now save the contact form information in the database, queue the email for sending, and then return the response. The email will be added to the queue to be processed once the response has been received back to the user’s web browser. This eliminates the need to wait for the email to be received before responding.
Use HTTPS with SSL
When dealing with sensitive material, HTTPS should be used instead of the HTTP protocol. It will give your website a protective shield against any harmful attacks that may jeopardize important information. An SSL certificate is regarded as the finest approach for safeguarding the application. Customers will trust you more if you have an SSL certificate because it confirms your identity on the internet and secures your data. For Laravel applications, HTTPS with SSL is recommended.
HTML Minification is Essential for Laravel Performance Optimization
We preserve gaps between the code during HTML markup to make it easier to read. The browser is unconcerned with the gaps, but it does increase the size of our HTML file, adding overhead to the system and making it sluggish. By using Laravel middleware to unify the HTML, you may reduce the size of the HTML page.
HTML minify middleware can be created with the command below for unifying the HTML on-page request.
php artisan make:middlewareHtmlMinifier
if (strpos($contentType, 'text/html') !== false) {
$response->setContent($this->minify($response->getContent()));
}
return $response;
}
public function minify($input)
{
$search = [
'/\>\s+/s',
'/\s+</s', ]; $replace = [ '> ',
' <', ]; return preg_replace($search, $replace, $input); } }
//Add the middleware into kernel
.phpfile into $routeMiddlewareGrouparray. protected $routeMiddleware = [ ..., ..., 'HtmlMinifier' => '\App\Http\Middleware\HtmlMinifier',
]
This middleware can now be used in the route file.
This middleware will automatically do HTML changes and respond to the user for every request made on-site.
Route::group(['middleware'=>'HtmlMinifier'], function(){
Route::get('/', '[email protected]');
Route::get('/{slug}', '[email protected]');
...
...
});
Also Read: Significance of Laravel Maintenance & Support Services
Consider Using Lumen
If you’re building an application that just requires basic features and does not require the full-stack framework, you should consider using the LUMEN framework from Laravel. Lumen is a micro-framework that is easy to use and fast in nature.
Laravel has spent a lot of time and effort developing this framework. The only features are those that are required and used by the majority of apps. It doesn’t require several configurations because most of it is built-in.
Minify Blade View
Always minify the views to improve the responsiveness of the page; the compressed version should be stored on the production server. The majority of the views are compiled by Laravel, although they are not minified.
To minify your blade views, utilize the Laravel HTMLMin package. Internally, this package uses Mr. Clay’s minify packages to reduce the response size as well as the blade view size at compilation time.
Minify CSS & JS to Improve Laravel Performance
Before you bundle the CSS and JavaScript files in the environment, you should always compress them. This will improve the user experience while also reducing HTTP calls. It’s a fantastic performance-improvement tip.
There are various tools for compressing and converting these files into a single file. You can bundle and minify CSS and JS files using Laravel-packer. If necessary, images can be compressed to create thumbnails.
Use New Relic
New Relic is an easy-to-integrate performance monitoring solution for Laravel applications. You can use New Relic to identify the queries that are taking the longest. It can indicate where the slowest queries are taking the most time. New Relic assists you by generating your Apdex score and comparing your app to others on the market. It can aid in the monitoring of availability and errors. You can create alert policies depending on your chosen thresholds.
.htaccess Optimization
Laravel .htaccess optimization might aid in the growth of your website. Enabling browser caching, HTML compression, and Gzip compression can all assist to increase page speed. Reduce browser caching to reduce server load, which is one of the simplest ways to improve speed. Browser caching saves resources on the machines of visitors. When they visit another page or return to your site later, the cached copy of the image or other type of file can be fetched from the visitor’s machine, saving bandwidth and server burden.
Note: The
.htacess file
is critical for the server, and it has a significant impact on the LINUX server. Please make a backup copy of the file before making any modifications
## EXPIRES CACHING ##
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType application/javascript "access 1 month"
ExpiresByType application/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 2 days"
# GZIP COMPRESSION
# compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
# compress HTML
SetOutputFilter DEFLATE
# GZIP COMPRESSION
Use Pusher or Similar libraries for Live messages
Pusher is a real-time program that allows you to send out notifications in real-time. Laravel comes with built-in support for Pusher, making developing real-time apps with Laravel and Pusher a breeze. It makes it simple for us to integrate our app with Pusher directly. Pusher has quickly become one of the most popular tools for creating real-time applications in the community.
have a unique app Idea?
Hire Certified Developers To Build Robust Feature, Rich App And Websites
Wrapping Up
With this, we conclude our ultimate guide on how to optimize your Laravel powered website. Make use of these tips and tricks to boost your Laravel website performance.
Also Check: