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.

✨ Vultr and Linode are back on Cloudways! VIEW PLANS→

17 Tips for Laravel Performance Optimization in 2024

Updated on October 26, 2023

14 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?

Laravel is commonly used for creating business information apps that are critical to a company’s success. These apps support decision-making for management and need to be fast and efficient. That’s why businesses need to focus on optimizing their Laravel apps for better performance.

Businesses typically use Laravel to build their information systems and enhance performance. However, it’s essential to optimize the Laravel app to ensure smooth execution and project deployment, especially for management information systems that drive crucial business choices.

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: When your Laravel app performs better, it becomes more effective, increasing your chances of reaching a wider audience and promoting business growth.
  • Efficient Development Environment: An optimized Laravel app streamlines coding tasks, enabling developers to save time, complete assignments faster, and allocate fewer resources.
  • Improved Traffic Handling: Utilizing the Laravel queue system helps your app manage increasing requests and handle surges in traffic more effectively as your site expands.

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.

Recommended Versions To Use

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

Laravel performance optimization improves user experiences, cuts server load, and lowers costs. By optimizing queries, using caching, and minimizing resource-heavy tasks, Laravel speeds up content delivery, reducing page load times.

Optimizing Laravel apps boosts server efficiency to handle more traffic without costly upgrades. Well-optimized apps scale smoothly, maintaining responsiveness and user experience as they grow.

Plus, optimized apps are simpler to maintain and troubleshoot by preemptively addressing bottlenecks and performance problems.

Supercharge Your Laravel Performance with Cloudflare Enterprise!

Automatically optimize images, minify CSS & much more starting from just $4.99/domain

Tips to Improve Laravel Performance

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 Horizontal Scaling

Consider using horizontal scaling if your API starts receiving a high traffic volume. This strategy involves spreading the workload across multiple servers, allowing your application to handle more simultaneous connections and requests.

In the context of Laravel, when traffic increases, you can deploy additional server instances to share the load. This prevents servers from becoming overwhelmed, ensuring quick and consistent responses.

Horizontal scaling also provides redundancy and fault tolerance. Even if one server encounters problems, the system continues to function, improving the overall reliability of the application. By incorporating horizontal scaling into Laravel performance optimization, organizations can ensure a seamless and uninterrupted user experience.

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

Using Cloudflare CDN

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 to 8.2 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, and Laravel 10 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:

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 to Measure Laravel Performance (Monitoring Tools)

Measuring Laravel performance is essential to identify areas of improvement and optimize the application for better speed and efficiency. Here are some performance monitoring tools you can consider to measure Laravel performance:

Blackfire.io

Blackfire.io is a powerful performance profiling and debugging tool specifically designed for PHP applications. Blackfire.io provides developers with deep insights into their application’s performance and helps them identify bottlenecks and inefficiencies.

With Blackfire.io, developers can easily identify performance issues, either it is at code level, database queries, and external API calls.

Also, it integrates seamlessly with popular PHP frameworks like Laravel, Symfony, and more, making it easy to set up and start profiling your application.

Laravel Dusk

Laravel Dusk is an end-to-end testing tool provided by the Laravel framework, designed to simplify and automate browser testing for web applications. With Dusk, developers can write expressive and reliable browser tests using a fluent and easy-to-understand API.

Since Dusk is built on top of Laravel’s testing infrastructure, developers can write tests that interact with the application just like a real user would. Moreover Dusk provides support for running tests in headless browsers, which improves test execution speed and allows for easier integration into Continuous Integration (CI) pipelines.

LoadForge

LoadForge is a cloud-based load testing platform that helps developers and businesses stress-test their web applications and APIs. With LoadForge, users can simulate thousands of concurrent users to assess the performance and scalability of their websites or APIs under heavy loads.

LoadForge offers a user-friendly interface with real-time monitoring and detailed performance metrics, that simplifies the process of creating, running, and analyzing load tests. LoadForge empowers developers to ensure their applications can handle high traffic volumes and maintain optimal performance during peak usage

What is Cloudways ThunderStack?

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.

The ThunderStack custom stack has been designed to enhance the performance, security, and scalability of web applications hosted on Cloudways’ managed cloud infrastructure. By combining the strengths of Nginx, Varnish, Redis, Memcached, PHP-FPM, MariaDB, and other components.

  1. Nginx Web Server:

Nginx is a high-performance web server and reverse proxy server known for its efficiency and speed. It’s designed to handle a large number of concurrent connections while consuming fewer resources compared to traditional web servers like Apache.

  1. Apache Web Server:

While Nginx is the primary web server, ThunderStack also allows the option to use Apache in conjunction with Nginx. This setup is known as a reverse proxy, where Nginx handles initial requests and serves static content, while Apache is used to process dynamic content.

  1. Varnish Cache:

Varnish is a powerful caching technology that sits in front of the web server and stores a copy of frequently accessed content in memory. This significantly reduces the load on the web server and improves the delivery speed of static content.

  1. Redis and Memcached:

Both Redis and Memcached are in-memory data stores that provide caching and session management capabilities. They help improve database query performance and reduce the load on the server by storing frequently accessed data in memory.

  1. PHP-FPM:

PHP-FPM (FastCGI Process Manager) is used to manage and optimize PHP processes. It ensures efficient processing of PHP scripts, leading to improved performance and response times.

  1. MariaDB Database:

ThunderStack employs the MariaDB database management system, a high-performance fork of MySQL. MariaDB is known for its speed and reliability, making it an excellent choice for database-intensive applications.

  1. CloudflareCDN:

Cloudways uses Content Delivery Network (CDN) service that integrates seamlessly with ThunderStack, highly regarded network service that aims to improve website performance, security, and reliability. Cloudways uses Cloudflare to optimize the delivery of web content.

  1. PHP Version Support:

PHP is a scripting language widely used for web development. Cloudways supports multiple versions of PHP, allowing you to choose the one that best fits your application’s requirements.

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

ThunderStack aims to provide an optimized environment for applications of all types, including content management systems, e-commerce platforms, and custom web applications.

 

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 with PHP hosting 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)

Q: How can I improve the loading speed of my Laravel application?

A: Here’s how you can improve the loading speed of your Laravel application:

  • Keep Laravel up to date.
  • Choose appropriate packages.
  • Utilize Artisan commands.
  • Cache configuration and routes.
  • Remove unused services.
  • Optimize classmap and Composer autoload.

Q: Are there any performance testing or profiling tools available for Laravel?

A: Yes, Laravel provides a built-in profiler as a performance testing and profiling tool. It allows you to measure code performance, identify slow-running code, detect memory leaks, and uncover potential performance issues within your Laravel application.

Q: How do I monitor and analyze the performance of my Laravel application?

A: You can monitor your Laravel application’s performance by employing the following techniques and tools:

  • Use a monitoring tool like Laravel Telescope, New Relic, AppDynamics, Scout APM, or Datadog.
  • Use logging to track events, errors, and exceptions with Laravel’s logging system.
  • Employ performance profiling using Laravel’s built-in profiler to measure code performance and identify issues.
  • Monitor server metrics tools like Nagios, Zabbix, or Munin to track CPU, memory, disk, and network usage.
  • Implement automated testing and write tests to validate code correctness and measure performance.

Q: What are some best practices for optimizing Laravel application code?

A: Follow the below best practices to optimize your Laravel application’s code:

  • Optimize database queries by using eager loading, indexes, and caching.
  • Profile and optimize your code to address performance bottlenecks.
  • Leverage caching mechanisms and HTTP caching headers.
  • Optimize autoloading, minify and combine assets, and process tasks asynchronously with queues.
  • Compress and optimize images, handle routes efficiently, enable OpCode caching, and implement proper error handling.
Share your opinion in the comment section. COMMENT NOW

Share This Article

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!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now