Optimizing Eloquent Query Performance Example In Laravel

Hello Laravel Devs

Hope you are doing well in this situation. Now in this tutorial i am going to discuss about laravel query optimization technique. So how you we can optimize our Laravel eoquent query and make faster our application. 

You know that Laravel provides many ways to write a query for a specific problem. That's the problem. In this situation for a large scale application, it is very important to write a faster query that consume a less memory and has to be executed faster. 

See the below example:

Destination::with(['flight' => function($query){

	return $query->->orderBy('arrived_at', 'desc')->first();

}])->get();

 

Look we want to fetch only last arrival flight. So here we have eager loaded our query with flight. Look here every destination has a flight. And in this situation two query are going to be executed. But we can easily optimize this query by using sub query.

Using those sub query we can improve our query perfomance. Laravel improve performance is the key thing of todays topic. Sometimes laravel eager loading is not the best solution. There might have best solution than eager loging. See the below example of code.

See the below example:

use App\Models\Destination;
use App\Models\Flight;

return Destination::addSelect(['last_flight' => Flight::select('name')
    ->whereColumn('destination_id', 'destinations.id')
    ->orderBy('arrived_at', 'desc')
    ->limit(1)
])->get();

 

Recommended : Laravel whereHas and whereDoesntHave Query Example

 

Look here. This query will gives us more better perfomance than before query with eager loading.It also reduce memory usage for your application. You can check it by installing Laravel debug bar and share with me what is happening. That's it.