This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

12 Tips for Laravel Performance Optimization in 2022

Updated on January 3, 2023

10 Min Read
laravel performance

Laravel has become a popular framework for developing business-focused applications and eCommerce platforms. Its popularity mainly stems from the optimized performance that lets developers finetune their Laravel apps’ performance.

Laravel has developed rapidly and is included among the leading PHP frameworks of 2023 thanks to its consistent finetuned execution. It is a one-stop PHP development framework to build anything from simple web applications to complex APIs.

This article explicitly focuses on improving your Laravel store’s performance by following the best optimization tips. To demonstrate the ideas discussed in this article, I will use an Employee Management System in Laravel.

Why Should Businesses Focus On Laravel Performance Optimization?

A framework’s structure and the associated libraries ensure that developers create powerful code with minimum effort. However, you can still optimize the code to ensure smooth performance even after deployment.

Laravel is often used to build business information applications, and Laravel-powered applications have severe implications for the business’s success. The management information systems that provide decision-making support to management layers must be fast and high performing at all times, so businesses trust Laravel for performance assurance.

Improve Your Laravel App Speed by 300%

Cloudways offers you dedicated servers with SSD storage, custom performance, an optimized stack, and more for 300% faster load times.

Prerequisites

For this tutorial, I assume you have a Laravel application installed on a web server. My setup is

To ensure that I don’t get distracted by the server-level issues, I have used Cloudways Laravel hosting because it takes care of server-level issues and has a great devstack to host Laravel projectsYou can also try Cloudways’ services for free without even entering your credit card details.

You might also like: Enhanced Cloudways Staging Environment Is Now Available for All Users

Benefits of Laravel Performance Optimization

Generally, businesses use Laravel to build their information systems and improve performance. But you must optimize the Laravel application for your business benefits to ensure smooth execution and deployment of your projects.

The Laravel management information system enables you to make crucial business decisions. And optimizing your Laravel app will surely boost the progress of your business prospects.

Even if you have created an incredible Laravel application, there’s always room for improvement. Enhancing your Laravel performance encompasses several benefits, including:

  • Boosted business growth: Improved Laravel performance means a more proficient site or application, increasing your chances of reaching a vast audience.
  • Smoother development environment: An optimized Laravel app helps developers save more time on coding, execute tasks faster, and spend fewer resources.
  • Better traffic handling: The Laravel queue system can help your site oversee request numbers as it develops and gets high traffic surges.

Tips to Improve Laravel Performance

  1. Config caching
  2. Routes caching
  3. Remove Unused Service
  4. Classmap optimization
  5. Optimize Composer
  6. Limit Use Of Plugins
  7. JIT Compiler
  8. Choose a faster cache and session driver
  9. Cache the queries results
  10. Use “Eager Loading” of Your Data
  11. Precompile Assets
  12. Use CDN for delivering your static assets.

Config Caching

Laravel provides the Artisan Cache Config command that helps in performance boosts. Here’s how you can use the command:

php artisan config:cache

Once you cache the config, any changes you make won’t have any effect. If you wish to refresh the config, rerun the above command. Use the following command to clear the config cache:

php artisan config:clear

You should refrain from executing the config cache command during local development as the configuration settings may require frequent changes throughout your application development.
You can use OPcache to optimize the application further, which 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 many routes and configurations. It is a simple array and helps speed up Laravel performance due to faster array loading. Execute the following command to route caching:

php artisan route:cache

Remember to run the command every time the config or route files have been changed. Otherwise, Laravel will load old changes from the cache. Clear the cache by using the following command:

php artisan route:clear

You might also like: An Introduction To Routing In Laravel

Remove Unused Service

Laravel’s primary goal is to ease the development process for developers. Once you launch Laravel, it auto-loads many service providers listed within the config/app.php file to help you get started with your project.

You don’t usually need services like View Service or Session Service. In addition, many developers don’t follow the default framework settings. So you should disable the unnecessary services to optimize Laravel’s performance.

Classmap Optimization

Laravel calls multiple files to include requests, so even a mid-level Laravel app will have many files.
A simple trick is to declare all the included files to include requests and combine them in a single file. Thus, a single file will be called and loaded for all include requests. For this, use the following command:

php artisan optimize --force

Optimize Composer

Laravel uses a separate tool called Composer to oversee different dependencies. After installing Composer, it loads dev dependencies into your framework by default.

These dependencies help develop websites. But once your site is completely operational, they’re not required and will only slow down your website.

composer install --prefer-dist --no-dev -o

The above command line allows Composer to make a separate directory for autoloader optimization. It requests the official distribution to be retrieved and packaged with no dev dependencies.

Limit Included Libraries

The good thing about Laravel is the massive number of libraries you can include in an app. But it comes with a high level of drag that the application experiences, ultimately slowing down the overall experience.

This is why reviewing all the libraries’ data recalled within the code is important. If you can work without a library, remove it from the config/app.php to speed up your Laravel app. Composer.json is another essential place to review.

Get Ready for Core Web Vitals Update

Ebook to Speed Up Your Website Before You Start Losing Traffic.

Thank You

Your list is on it’s Way to Your Inbox.

JIT Compiler

Translating PHP code to bytecode and then executing it is a resource-intensive process. This is why a go-between, such as Zend Engine, is required to execute the C subroutines. You must repeat the process every time the app is executed.

Ideally, this process should only be carried just once to save time, and that’s exactly where the Just-in-Time (JIT) compilers jump in. 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. Caching backend, like Memcached, is among the fastest cache and session drivers for Laravel 9 performance.

The driver key for changing the session driver is usually located in app/config/session.php, and the 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 frequently executed query results is an excellent way of improving Laravel 9’s performance. For this, I recommend the remember function, which 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 Eloquent, a great ORM to deal with databases. It creates models that abstract the database tables from the developers.

Using simple structures, developers can 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, adding to the application’s response.

Let’s compare lazy loading and eager loading. The lazy loading query will look like this:

$books = App\Book::all();

foreach ($books as $book) {

echo $book->author->name;}

In contrast, eager loading query will look like:

$books = App\Book::with('author')->get();

foreach ($books as $book) {

echo $book->author->name;

}

You Might Also Like: Improve MySQL Performance With This Guide

Precompile Assets

Developers often distribute code into separate files for Laravel application tuning. While this keeps the code clean and manageable, much more is needed to 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 them directly from the server that hosts the files) will improve Laravel application performance.

Once a client visits a site, some information is served from the closest Cloudflare CDN< area, which results in quick page stack speed and an incredible affair for the client.

Cloudflare CDN is a benefit-based CDN, implying you must characterize the static resources (JS, CSS, HTML, pictures, recordings, liveliness, etc.) on a specific application.

Assets Bundling

Laravel Mix comes by default with all Laravel applications. Using common CSS and JavaScript preprocessors, it provides an effective API to define Webpack build for your PHP applications.

I will use Laravel Mix to compile application assets, including scripts, styles, and more. Using Laravel Mix, 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 a CSS file named 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.

Doing so will reduce the number of HTTP requests 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 could result in a huge file. As a result, this practice will not allow our application to benefit from the proposed compilation. Therefore we can minify our assets using Laravel Mix to resolve this issue.

$ npm run production

The above command will run all Mix tasks and ensure our assets are production-ready. Once minified, the assets will become smaller in size and hence will be retrieved faster, speeding up our application’s performance.

Running the latest version of PHP

PHP’s latest version has brought significant performance improvements. So you must ensure your Laravel application is running the latest PHP version to tap all the performance improvements introduced in your app’s new version, otherwise, you’ll experience performance speed and security issues. You can check out the PHP benchmarks to learn more.

Cloudways offers PHP 7.4, 8.0, and 8.1 on its platform so users can optimize their apps with flawless speed and performance using advanced functionalities. You can use the latest Laravel version, i.e., Laravel 9, on the Cloudways platform.

The platform allows you to easily upgrade your previous PHP versions to newer versions with a click.

Laravel Debugbar

Though not an optimization technique but a package that can also be used as a Laravel performance monitor. Laravel Debugbar helps you integrate PHP Debug Bar with Laravel 9 and includes a ServiceProvider to register the debugbar and attach it to the output.

We recommend using this package while developing your application to inspect your application and 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:

  1. Laravel page speed composer package
  2. Update provider details
  3. Publish the package
  4. Register your Middleware
  5. Make route over a page
  6. Create Blade File
  7. Run app

Laravel page speed composer package

Download and extract the renatomarinho/laravel-page-speed package using Composer. 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 extracting the package, go to the config/app.php file to append service provider and alias details with specific classes.

'providers' => [

....

....

RenatoMarinho\LaravelPageSpeed\ServiceProvider::class,

],

Publish the package

After adding provider details, we need to publish the particular package to implement in our application. The following command helps us to publish the package, and we can use the package only after executing this command:

php artisan vendor:publish --provider="RenatoMarinho\LaravelPageSpeed\ServiceProvider"

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' => [

       ........

       ........

       \RenatoMarinho\LaravelPageSpeed\Middleware\InlineCss::class,

\RenatoMarinho\LaravelPageSpeed\Middleware\ElideAttributes::class,

\RenatoMarinho\LaravelPageSpeed\Middleware\InsertDNSPrefetch::class,

\RenatoMarinho\LaravelPageSpeed\Middleware\RemoveComments::class,

\RenatoMarinho\LaravelPageSpeed\Middleware\TrimUrls::class,

\RenatoMarinho\LaravelPageSpeed\Middleware\RemoveQuotes::class,

\RenatoMarinho\LaravelPageSpeed\Middleware\CollapseWhitespace::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

At the end, create a blade file and include a set of our code to display.

How Our Custom Stack Boost Performance

Cloudways stack

Our custom stack, known as ThunderStack, is specially built to boost the performance of Laravel apps. The winning recipe comprises Apache and NGINX, Varnish, and Memcached.

You can choose MySQL or MariaDB as your database and enable Redis as a session driver or configure Varnish according to project needs.

You might also like: PHP 5.6, 7.0, 7.1, 7.2, 7.3, 7.4, and 8.0: Performance Benchmarks for WordPress

 

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.

Facebook

Hoang LeHoang .

Backend: Reduce db query and use cache Frontend: Combine and minify js/css, use lossless method to compress images

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.

Q: How can Redis help improve Laravel’s performance?

A: You can use Redis 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, cache, or even a message broker.

Q: How to test Laravel Website Performance?

A: There are several website performance testing tools that 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: You can optimize the PHP sites on four different levels:

  • Language-level:Using the language’s latest version to avoid specific coding styles in the language that may slow down your code.
  • 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 like Cloudways.

Q: Which tool to use for Minifying and Bundling Assets?

A: Laravel Mix is an effective tool for defining Webpack builds for PHP applications. It concatenates multiple assets like CSS into a single file and reduces multiple HTTP requests to one, helping 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)

Share your opinion in the comment section. COMMENT NOW

Share This Article

Customer Review at

“Cloudways hosting has one of the best customer service and hosting speed”

Sanjit C [Website Developer]

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]

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Unleash The Cloud.
Not Budgets.

For 4 Months +
Up To 30 Free Migrations

Cyber Week

SAVINGS
Time Left In Offer
  • 0

    Days

  • 0

    Hours

  • 0

    Minutes

  • 0

    Seconds

40% OFF

On All Plans

GET THE DEAL NOW