Let’s get started! Let’s say your Laravel application is already in production.

From the first user, to the tenth, to the hundredth, to the thousands of users! Slowly, the more users you get, the slower your site gets

So what should we do? The devil is in the details

After some searching, I decided to write down these 20 tips to speed up your website

I’ll start with the basics, most of which can be done instantaneously. Then, I’ll step up the difficulty. Finally, the more advanced stuff. If you follow my steps step by step, I believe your site will improve.

Enjoy your learning journey! If you have any suggestions, leave them in the comments below! I’m happy to discuss it with you.

Basic optimizations

Let’s see what we can do in just a few seconds.

1. Route cache

Each time the server executes a request, all routes are registered, which takes some time. However, you can skip this step by choosing to cache the route list.

Caching the route list is very simple. What you need to do is to execute the following command after deploying the application:

php artisan route:cache
Copy the code

However, if you add or modify any routing information, do not forget to clear the previous cache and re-execute the cache command.

php artisan route:clear

# then, execute again
php artisan route:cache
Copy the code

Note that this is only valid for controller class routes.

2. Configure cache

Just like routing, you can also cache configuration files in your application.

Imagine this scenario: Every time you send a request to your App, Laravel needs to load a different configuration file and open a *. Env * file to read its contents. It’s not very efficient, is it?

But don’t worry, there’s an Artisan order for that.

php artisan config:cache
Copy the code

You can use it after deployment. Just like routing, don’t forget to clean up the cache when you edit something.

php artisan config:clear

# Then, one more time...
php artisan config:cache
Copy the code

3. Optimized Composer automatically loads

In general, Composer generates auto-loading files very quickly. However, in a production environment, this can be slow if the PSR-4 and PSR-0 autoload rules are set.

You can optimize the auloader file creation process by adding the following command to the deployment script.

$  composer dump-autoload  -o
Copy the code

Don’t forget it.

4. Myth: “Don’t use Blade view too much”

I’ve heard enough of this rumor.

“Never use a Blade view too much, because it can degrade application performance!”

What a big lie! Serious face!

Keep this in mind: Laravel compiles the Blade view. Compilation means that at the end of the process, you will have one complete compiled file instead of using multiple files.

So, there is no need to worry.


Intermediate dry

5. Find another/better Cache/Session driver

By default, the Cache and Sessions drivers are “files” when you create a new Laravel project. It’s fine in local development environments and small projects, but it gets bigger as the project grows.

So, consider switching to a better driver such as Redis. Laravel has a built-in way to support it, and all you have to do is install Predis.

More details here and here.

6. Upgrade Laravel as soon as possible

Remember to upgrade Laravel as soon as possible when a new version is released. It’s not just about new features: whenever possible, all contributors spend time fixing performance issues around the code base.

So keep an eye on your code and keep it up to date.

7. Delete unused services

This is a trick that a lot of people forget. Ask yourself:

“Do I need it? *

We know that Laravel comes with a lot of services, after all, it’s a full-stack framework, and every service has its place.

So take some time to check the *config/app.php * file and see if you can find a service you don’t need. If all is well, try to remove it and test your application.

It should help (a little bit)!

8. Use preloading to query information

If you know what a Laravel is, you probably also know what preloading is. Preloading is a way to improve Eloquent performance, if you are not up-to-date, by using a specific syntax to reduce the number of queries sent to the database.

This problem is called the N + 1 query problem. Let’s take an example. You have two models: Book and Author. Every book has its author.

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

foreach  ($books  as  $book)  {
    echo  $book->author->name;
}
Copy the code

Imagine that you have 1,000 books in your database. This code will now perform ** 1001 ** queries to retrieve the author names of the 1000 books.

1 (query to get data for 1000 books) + 1000 (query to get author data for each book) = 1001.

But if you write code like this

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

foreach  ($books  as  $book)  {
    echo  $book->author->name;
}
Copy the code

Change the underlying query to avoid this performance issue. You will only execute two queries instead of 1001! That’s a huge performance boost.

9. Cache query results

Sometimes it might be a good idea to cache a specific query result.

Imagine this scenario: You’re about to display the top 10 albums list on your app’s home page. This is done by executing queries from the database (queries may involve the artists table, as well as other tables). You get 1,000 page views per hour.

If the number of queries for this leaderboard data is 1000 per hour, that’s 24,000 queries executed over the course of the day. For now, let’s assume that this list is updated every hour. How about caching the results of each query for an hour?

$value  =  Cache::remember('top_10_albums', 60.function  ()  {
    return  Album::with('artist'.'producer')->getTopTen();
});
Copy the code

The * remember* method of the cache component will fetch the data from the database and cache it for 60 minutes if no cache is found. After expiration, the latest data is fetched from the database again, updating the cache.

Queries range from 24,000 to 24 times per day.

10. Index your table

Remember to index your tables when necessary. This may seem like a no-egg tip, but it’s actually necessary. Because I’ve seen a lot of applications where the data table doesn’t have an index.

The implementation is simple, you can create a new database migration and use the methods inside to add indexes.

Schema::table('my_table_name'.function(Blueprint  $table) {$table->index('field_to_be_indexed');
});
Copy the code

Of course, you don’t just create an index where you like it. You must study your business, code, and queries to see where the indexes are most needed, and then build them.

11. Too much middleware?

Laravel makes a lot of (pre/post) calls to the middleware you’re registered with. So, go through them and eliminate any middleware you don’t need.

The usual list of middleware is * kernel.php *.

It’s time to use queues!

There are times when Laravel is slower than expected and you can consider executing tasks asynchronously.

The most common scenario is to send a welcome email and let’s go through the process.

  1. Users fill out our forms;
  2. Write his/her details to the database;
  3. Send him or her an email with a welcome and confirmation link.
  4. And display a thank you page;

Most of the time, these tasks are entirely in the controller and are executed sequentially.

My suggestion is that by learning how to use events and queues, you can delegate the task of sending mail to a dedicated process to improve the user experience.


Advanced dry

13. Improve asynchronous queues with Pusher

I wrote a little bit about queues up there. Sometimes, you can also use queues to improve user-facing tasks.

Imagine that you are creating a heavy (computationally) process and want to show the user a progress bar for that task. You can easily use queue asynchronous tasks and integrate Pusher to send messages to the front end for this purpose, even if the task is not completed.

Another frequently used example is sending a message to the user without refreshing the page.

Think about it!

14. Use the Logs/Debugbars/Laravel Telescope measurement debugging tool

There is one of my favorite quotes about self-improvement. From my CEO (thank you Massimo!) To quote Peter Drucker.

If you can’t measure it, you can’t improve it.

This concept fits well in the context of a Web application. Many things need to be measured to improve request management time for Web applications. Fortunately, we have a lot of very good tools to do this.

  • Slow logging: MYSQL, MariaDB, and other databases can enable slow logging to track statements that take a lot of time. You can use this data to determine if specific code (or queries) must be changed or optimized;

  • Debugbar: Laravel Debugbar is a great extension package. In many applications, you can use it to collect data. Queries, views, times, and so on;

  • Laravel Telescope: Another really cool tool is Laravel Telescope, billed as an “elegant debugging assistant” for Laravel applications. If you’re interested, I’ve written an article about it here;

15. Update your PHP version

While this seems simple, it can be cumbersome to implement if your project is large enough, so I thought I’d add it to the list of advanced techniques.

If your PHP version is under 7.0, update your PHP and laravel versions.

16. Use Lumen on the server

If your application’s data volume is growing significantly, you may want to consider service splitting for your system. However, there is no clear-cut method guide to guide you through it: how high or low the split criteria are depends on many factors ranging from the domain of the application to the effort required to split everything necessary.

But once you do, your project gets a new lease of life.

If you are interested in this topic, you can go to medium.com/munza/larg… Start.

17. Provide CDN services for static resources

I’m pretty sure you have a lot of front-end resources like CSS files and JS scripts.

You can reduce the amount of data sent to users in a number of ways:

  • Compress static resources;
  • Bundling static resources (combining multiple CSS files or JS scripts into one to reduce the number of requests)
  • Enable gzip compression.

However, if you encounter a lot of traffic, you can host your static resources to a dedicated CDN server, such as:

  • Akamai;
  • Max CDN;
  • Cloudflare;
  • Amazon AWS Service (S3 + CloudFront);

In China, youpaiyun and Qiniuyun can be used

18. Use advanced measuring tools

Installing Laravel Debugbar or Telescope would be a good start, but for bigger projects, it won’t be enough.

You need to select a more advanced tool, as follows:

  • New Relic;
  • AppOptics;
  • Datadog;
  • Sentry;

The applications listed above do not do the same thing: they are designed for different purposes. Take the time to learn from them to understand how they can help.

19. Vertical scaling

You’ve polished every detail of your code from top to bottom, but your app is growing. Sooner or later you have to scale vertically.

There’s a simple way to put it: more RAM, more space, more bandwidth, and more CPU

Note that this is a common practice for many startups that don’t have enough time to schedule refactoring/optimizations. It’s a good idea, so you can think of it as a temporary solution that will give you a break.

20. Scale horizontally

Horizontal extension is another way of extension, which is different from the traditional vertical extension. It has two main points:

  • Instead of adding hardware resources to your existing configuration, you’ll probably add more functional modules to handle the increased traffic. In a vertically scale-out environment, you only need to increase the server configuration, but scale-out horizontally means that your application will be deployed and run on different machines, possibly behind a load balancing machine or other service. This means more setup and configuration; Now things are not so simple;
  • Not all applications scale quickly, and sometimes you need to refactor and isolate code; Sometimes you need to break up your application into smaller services of different sizes.

Scaling horizontally is a lot to do, but once you can scale your application horizontally, the benefits are incredible.

conclusion

Enough for today! I created this list by combining my personal experience with some of the research I’ve done before.

Feel free to come up with something new if you like, and I’ll be happy to update this post accordingly.

From https://learnku.com/laravel/t/24559