A website speed very important key for success of website. it’s an important key for SEO. Therefore, whenever we write any code in Laravel projects, we should try to make sure to optimise the code.
I am giving you some techniques for quick performance improvements.
Steps-
- Only select the field which you need in view/blade file.
- Use eager loading whenever possible
- Remove unused package
- Cache
- Use the latest version of PHP
1. Only select the field which you need in view/blade file
This one is the most easy way to improve speed, this will transfer the data which is required to show or operations.
For more understanding see example.
$users = User::all(); foreach($users as $user) { }
We are selecting all the data which will a heavy data transfer, So always try to use like below.
$users = User::select(['id', 'name', 'email'])->get(); foreach($users as $user) { }
2. Use eager loading whenever possible
Whenever we are make relation with model, try to use eager loading.
See the example of below , we have two model one is user and second is address model. Here is one-to-one relationship between them.
Without eager loading, your code will be like below.
$users = User::all(); foreach ($users as $user ) { print_r($user->address->country); }
With eager loading code will be like below
$users = User::with('address')->get(); foreach ($users as $user ) { print_r($user->address->country); }
3. Remove unused package
Open your composer.json file, check the packages, if any of them , you are not using in project, Just remove. If possible always try to create your own code for replacing the package.
4. Cache
This is also an easy way to improve the speed. In laravel we can cache the database query, This will improve the speed. First see with out cache.
$users = DB::table('users')->get();
See with cache
$users = Cache::remember('users', 120, function () { return DB::table('users')->get(); });
The above code uses the remember() method. If the cache contains any items with the key users. It returns the cached value. If it doesn’t exist in the cache, the result of the DB::table(‘users’)->get() query will be returned and also cached.
The item would be cached for 120 seconds.
5. Use the latest version of PHP
Always use new version of PHP that comes with performance and speed. This will might be difficult to change, but this will help us to secure and speed up website.