Home PHP Framework Laravel Recommended 18 essential tips for Laravel performance optimization

Recommended 18 essential tips for Laravel performance optimization

Aug 11, 2022 am 09:55 AM
laravel

Laravel is a popular open source PHP framework known for its strong security and simple yet complex coding architecture. It's a great choice for building cutting-edge web applications that drive revenue and grow your business.

Today, there is no PHP developer who is not influenced by Laravel. They are either junior or mid-level developers who like the rapid development that Laravel offers, or they are senior developers who are forced to learn Laravel due to market pressure.

With over 1 million websites powered by Laravel, Google has pushed the importance of website speed, and users are increasingly unwilling to accept anything other than an incredibly smooth user experience. Some People are giving frameworks like PHP and Laravel a reputation for not performing as well as other frameworks. While this may well be true, it doesn't mean there's nothing you can do about it. So, in this guide, we’ll take a deep dive into how to optimize Laravel’s performance.

Currently, Laravel has become a very popular framework for developing business and e-commerce applications. Most organizations prefer to use Laravel to build their business applications. there are many reasons. But today we are only focusing on performance optimization.

Why is Laravel's performance optimization so important?

This article will introduce several important techniques and guide you in each step to optimize your Laravel website. While some of the steps may sound technical, they are easy to follow and recreate on your own screen.

1. Route caching

Laravel allows caching of routes. You can execute the Artisan command:

php artisan route:cache
Copy after login

All routes will be cached in the routes.php file.

The next time routing is needed, the cache will be accessed instead of the routing file. This can improve site performance by routing requests quickly.

To clear the cache, you can use a command similar to:

php artisan route:clear
Copy after login

Route caching is a simple way to make your website smoother and load faster.

2. Use Artisan commands effectively

One of the best features of Laravel is its command line tool Artisan. If used effectively, it can improve the performance of your application.

You can cache routes and configurations. You can execute the following command to cache configuration and routes:

php artisan config:cache

php artisan route:cache
Copy after login

Note: Artisan Optimize was removed in Laravel 5.5, it worked in previous versions.

php artisan optimize --force
Copy after login

Be sure to clear the cache when adding new configurations or new routes. The cache can be cleared effectively using the command below.

php artisan config:clear
php artisan route:cache
php artisan view:clear
Copy after login

3. Configure cache

Laravel provides a very interesting command: Artisan Cache Config, which Very helpful for improving performance. The basic usage of the command is:

php artisan config:cache
Copy after login

After the configuration is cached, it will not have any impact on the changes you make. If you want to refresh the configuration, just run the above command again. If you need to clear the configuration cache, use the following command:

php artisan config:clear
Copy after login

4. Get data directly

When you execute any query in Laravel , Laravel executes the query lazily (lazy loading), it only fetches the data when needed.

In some cases, this lazy loading behavior can increase the number of queries executed while reducing application performance.

Let's look at a simple example to understand this behavior in detail. If you want to get the author names of books in the library.

With lazy loading, you will end up executing N 1 queries to find the results. You can see it in the code example below.

$books = Book::all();
foreach ($books as $book) {
  echo $book->author->name;
  }
Copy after login
Copy after login

In the code below, the query is executed every time the for loop is executed. To solve this problem, Laravel allows you to load data directly.

This will increase your query execution time and reduce the number of queries. The code example below shows how we can easily load a complete list in one query.

$books = Book::with('author')->get();
foreach ($books as $book) {
  echo $book->author->name;
  }
Copy after login
Copy after login

Let’s look at a simple example to understand this behavior in detail.
If you want to get the author's name of the books in the library.

If you don't use eager loading, you will end up executing N 1 queries to find the results.
You can see it in the code example below.

$books = Book::all();
foreach ($books as $book) {
  echo $book->author->name;
  }
Copy after login
Copy after login

In the code below, each time the for loop is executed, a query is executed.
To solve this problem, Laravel allows preloading related data.

这会增加的查询执行时间并减少查询次数。
下面的代码示例展示了我们如何在一个查询中轻松加载完整列表。

$books = Book::with('author')->get();
foreach ($books as $book) {
  echo $book->author->name;
  }
Copy after login
Copy after login

5.  Composer 优化

Laravel 使用一个名为 Composer 的包管理工具来管理不同的依赖项。 当你最初安装 Composer 时,默认情况下它会将开发依赖项加载到你的系统中。

这些依赖项对于开发网站很有用。 但是,一旦你的网站完全投入运营,就不再需要它们,事实上,它们只会减慢速度。

当使用 Composer 安装包时,使用 --no-dev-o 参数来移除 dev 依赖:

composer install --prefer-dist --no-dev -o
Copy after login
Copy after login

此命令允许 Composer 创建用于优化自动加载器和提高性能的目录。 它只是请求获取和打包官方发行版,没有开发依赖项。

注意不要消除任何运行时依赖项。 这可能会危及网站的性能,甚至导致其崩溃。

6. 压缩绑定配置

Laravel mix 可以在这里为你提供帮助,它编译所有 CSS 并提供单个 app.css 文件,从而将多个 HTTP 请求减少为单个。 你还可以使用 laravel-mix-purgecss 包从项目中删除未使用的 CSS,只需将其安装在你的开发项目中:

npm install laravel-mix-purgecss --save-dev

# or

yarn add laravel-mix-purgecss --dev
Copy after login

在你的文件 webpack.mix.js

const mix = require('laravel-mix');
require('laravel-mix-purgecss');
mix.js('resources/js/app.js', 'public/js').sass('resources/sass/app.scss', 'public/css').purgeCss();
Copy after login

7. 队列

Laravel 队列就像你的 CPU 一样工作。 每当你的计算机处理一项任务时,它都会以最有效的方式执行,而不会降低用户体验的质量。 这意味着当你渲染文件或执行资源密集型操作时,你的 CPU 会确保你仍有剩余的处理能力用于其他任务,直到达到其限制。

例如,当用户注册到网站时,我们必须在后端执行许多操作,例如存储用户信息、发送激活邮件、发送欢迎邮件等。如果我们只是发送一封邮件(没有队列),那么它会大约需要 4-5 秒。并且用户必须等到请求。因此,对于队列,我们只需要在执行所需的验证并显示用户成功消息后将操作推送到队列中。之后,我们只需要在队列执行时处理基本的事务。

简单的例子是:

  • 发送电子邮件
  • 下载文件
  • 上传文件

这些任务不需要用户看到,可以作为后台进程完成。

Laravel 还有几个队列驱动程序支持文档,并为每个文档提供独特的解决方案,例如 Horizon,一个监控队列系统的仪表板。

8. 快速缓存或会话驱动程序

为了提高 Laravel 应用程序的性能,我们可以存储会话并将它们缓存在 RAM 中。 Memcached 是最好和最快的缓存和会话驱动程序。 Laravel 可以灵活地将一个缓存/会话驱动器切换到另一个。

对于会话驱动,我们可以在 config/session.php 中更改驱动键,对于缓存,我们可以在 config/cache.php 文件中更改驱动键。

9. 数据库索引

当我们谈论提高应用程序的性能时,我们会遵循 Laravel 中的许多实践,例如缓存、数据加载、资产缩小等。但是还有一件事可以帮助我们提高性能,即数据库索引。 这基本上是一种数据库级技术。

在技术实现的角度看,数据库索引是基于数据库表的一个或多个列的数据结构。索引背后的主要思想是加快数据检索。它有助于轻松定位数据,而无需在每次访问数据库时遍历每一行。

使用列,索引有助于最小化处理的每个查询的磁盘访问。使数据库索引成为一种强大的数据库优化技术还可以提高数据库的整体性能。

在 Laravel 中,我们可以使用迁移来创建索引。下面是示例:

Schema::create(‘users’, function (Blueprint $table) {
   $table->string(’email’)->index();
   });
Copy after login

10. 利用 JIT 编译器

PHP 是一种计算机机器和服务器端语言。它本身不理解 PHP 代码。通常,程序员使用编译器将代码编译成字节码并解释 PHP 代码。程序编译过程会影响 Laravel 应用程序的性能和用户体验。所以,Laravel 程序员可以使用 Zend Engine 自带的即时编译器来快速编译代码。

11. 压缩图像

如果你的项目中包含许多图像,你应该压缩所有图像以优化性能。
有一些方法可以进行优化。
但是不同的图像需要不同的工具来保持图像的质量和分辨率。

如果你使用 Laravel Mix,建议在编译图像时使用像 ImageMin 这样的 NPM 包。
对于非常大的图片,先试试 TinyPNG 压缩图片,然后再用 ImageMin 尽量压缩。

12. 视图缓存

另一个方面是视图缓存。
视图缓存存储编译后的的 Blade 模板以提高项目的速度。
你可以使用下面的 artisan 命令手动编译所有视图并优化性能:

php artisan view:cache
Copy after login

上传新代码时记得清除缓存;否则,Laravel 将使用你的旧视图,你将花费大量时间尝试解决此问题。运行以下命令清除视图缓存:

php artisan view:clear
Copy after login

13. 删除未使用的服务

你可以使用 Laravel 提供的服务容器框架轻松地注入服务。你只需在 config/app.php 文件中的 providers[] 数组中添加服务的名称。

但同时,你应该只打开你正在使用的那些服务。应停止所有其他未使用的服务。

你可以通过在 config/app.php 文件中注释掉这些服务来停止这些服务。这将减少你的应用程序启动所需的时间并提高其性能

14. 使用 CDN 加载静态内容

CDN 是在全球范围内加载静态内容的好方法。如果你的应用程序越来越流行,你可能需要为你的应用程序使用 CDN 服务

让我举一个简单的例子,你在美国的服务器上托管了你的应用程序。现在,如果你有来自印度的请求,你需要很长时间才能为该请求提供内容。

为了解决这个问题,CDN 应运而生。 CDN 可以帮你缓存多个静态页面。现在你的请求将首先到达 CDN,如果内容存在于 CDN 中,则直接提供页面。这极大地提高了你的内容服务速度以及最终用户体验。

15. 压缩 CSS 和 JS

在生产环境中实际捆绑这些文件之前,你应该始终压缩 CSS 和 JavaScript 文件。 这将增强你的用户体验并减少 HTTP 调用。 这是一个很棒的 Laravel 性能优化技巧。

有多种工具可用于压缩这些文件并将它们捆绑为单个文件。 你可以使用 Laravel-packer,它允许你打包和压缩你的 CSS 和 JavaScript 代码。 如果需要,你还可以调整图像大小以生成缩略图。

16. 移除开发依赖

首次安装 Laravel 或 composer 时,通常会默认将开发依赖项注入到你的系统中。 虽然这些依赖项确实有助于构建你的网站,但当你的网站启动并运行时,你不需要这些依赖项。

你可以通过 Artisan 输入这个简单的命令来删除这些依赖项:

composer install --prefer-dist --no-dev -o
Copy after login
Copy after login

注意: 开发依赖项不同于运行时所需的依赖项。 不要删除运行时依赖项,因为这可能会影响你网站的性能,甚至会导致你网站的某些部分崩溃。

17. 将Lumen用于小型项目

有时开发小型应用程序(例如移动或 Angular 应用程序)不需要使用像 Laravel 这样的全栈框架。 在这种情况下,请考虑改用 Lumen。

Lumen 是由 Laravel 的同一创建者开发的微框架。 就像 Laravel 的轻量级版本一样,Lumen 是关于微服务的速度和性能的。 在构建 Web 应用程序时,它需要最少的设置和替代路由参数,从而加快开发过程。

例如,Lumen 每秒可以处理 100 个请求。 你还可以集成来自第三方的工具或软件包以获得新功能。 此外,Lumen 支持所有平台并允许你升级到 Laravel。

18. 限制包含的库

Laravel 让你可以自由添加任意数量的库。 虽然这是一个很棒的功能,但添加大量库会给应用程序的性能带来很大压力。 它还会影响整个用户体验。

因此,扫描代码中当前使用的所有库数据至关重要。 你可以在 config/app.php 文件中找到这些库。 在检查库时,删除你知道对你不再有用的库。

查看 composer.json 中不需要的依赖项也是一个好办法。

感谢你们的阅读!

原文地址:https://devdojo.com/techvblogs/how-to-optimize-laravel-for-performance

译文地址:https://learnku.com/laravel/t/69775

The above is the detailed content of Recommended 18 essential tips for Laravel performance optimization. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to get the return code when email sending fails in Laravel? How to get the return code when email sending fails in Laravel? Apr 01, 2025 pm 02:45 PM

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

Laravel Eloquent ORM in Bangla partial model search) Laravel Eloquent ORM in Bangla partial model search) Apr 08, 2025 pm 02:06 PM

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

How to effectively check the validity of Redis connections in Laravel6 project? How to effectively check the validity of Redis connections in Laravel6 project? Apr 01, 2025 pm 02:00 PM

How to check the validity of Redis connections in Laravel6 projects is a common problem, especially when projects rely on Redis for business processing. The following is...

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Laravel's geospatial: Optimization of interactive maps and large amounts of data Laravel's geospatial: Optimization of interactive maps and large amounts of data Apr 08, 2025 pm 12:24 PM

Efficiently process 7 million records and create interactive maps with geospatial technology. This article explores how to efficiently process over 7 million records using Laravel and MySQL and convert them into interactive map visualizations. Initial challenge project requirements: Extract valuable insights using 7 million records in MySQL database. Many people first consider programming languages, but ignore the database itself: Can it meet the needs? Is data migration or structural adjustment required? Can MySQL withstand such a large data load? Preliminary analysis: Key filters and properties need to be identified. After analysis, it was found that only a few attributes were related to the solution. We verified the feasibility of the filter and set some restrictions to optimize the search. Map search based on city

Laravel and the Backend: Powering Web Application Logic Laravel and the Backend: Powering Web Application Logic Apr 11, 2025 am 11:29 AM

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Apr 18, 2025 am 09:24 AM

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

Laravel user login function Laravel user login function Apr 18, 2025 pm 12:48 PM

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

See all articles