Laravel Eloquent has many in-built functionalities for data layer, The one of them is eager loading on dataset. The Eloquent help to solve N+1 queries problem.The eager loading can drastically increase the performance of your application.
The eager work with relational data set, that mean you need to define relational between two tables or many tables.We can get associated model’s data for one of the models.
The laravel is providing two method to apply eager loading –
- load()
- with()
Both Eloquent method return the same results.The main difference between these two methods – with()
method loads all data of associated models with front model, Whereas load()
help to get all data of associated models based on condition.
For example, consider a Employee model that is related to Department. The relationship is defined like so:
class Employee extends Eloquent { public function dept() { return $this->belongsTo('Dept'); } }
We will get employee department name without eager loading, Please consider the following code:
$emps = Employee:all(); foreach ($emps as $emp) { echo $emp->dept->name; }
Above query will execute 1 query to retrieve all of the employees and , to get each employee department name will fetch using another query, so if we have 10 employee then N+1 times query will run, 11 times query will execute to get 10 employee data with department name.
The Eloquent eager help to reduce the number of queries.We can load department information of employee using with()
method.
$emps = Employee::with('dept')->get(); foreach ($emps as $emp) { echo $emp->dept->name; }
Above code will execute one query to get all employee and second query to get department name using in()
method, only two queries will be executed:
select * from employees select * from departments where id in ('account', 'hr', ...)
Eager Load Multiple Relationships
We can apply eager load on multiple relationships table at one time:
$emps = Employee::with('dept', 'salary')->get();
Eager Load Constraints
Sometimes you may wish to eager load a relationship tables, but also specify a condition for the eager load. Here’s an example:
$users = Employee::with(array('salary' => function($query) { $query->where('amount', '>', '25000'); }))->get();
In this example, We’re eager loading the employee salary data, but only if the salary amount column value is greater than 25K.
Lazy Eager Loading Using load()
We have used with()
method to get eager data load but sometimes you need to load associated model data based on condition, that time you need to use load()
method.
This may be useful when dynamically deciding whether to load related models or not, or in combination with caching.
$emps = Employee::all(); $emps->load('dept', 'salary');