Updated 28 January 2020
The Eloquent (ORM) in laravel is working great and provide simple ways to access the database. In this blog we will understand about what is lazy and eager loading in Laravel eloquent and how it’s works.
Eloquent Relation
First of all we need to define relationship between models. Here we will use two models, student and class. Student is belong to one class, and class has many Students. Let’s see the relationship in model :
class Student extends Model
{
protected $fillable = [
‘title’, ‘description’, ‘price’
];
public function class() {
return $this->belongsTo(‘App\Class’);
}
}
Lazy Loaded
By default, accessing data in eloquent is “Lazy loaded”, in the above code, we get all data in the student table, the query running behind that is:
1 |
select * from `student` |
From above step data in the relationship table (class) is not retrieved yet, if we want to access the data in the relationship table, we can access like this:
1 |
foreach ($student as $student) { echo $student->class->name; // this is lazy loaded } |
the query running behind that is:
select * from class
where class
.name' = ? limit 1
class
select * from where
cities.
name = ? limit 1
class
select * from where
cities.
name` = ? limit 1
…
Eager Loading
Sometimes it is useful to use eager loading in your application, suppose you are calling the data by using Ajax, in this case we have to use eager loading to prepare all data include the data in its relationship table before response result to ajax. To use eager loading, just add the with method to your eloquent.
1 |
$student = Student::with('class')->get(); |
Now all data in student and class in the relationship table will be load at same time.
In some case that is useful to eager loading dynamically, we can decide where data in relationship table need to load.
1 2 3 4 |
$student = Student::all(); if($isLoad) { $student->load('class'); } |
we use load method to load the relationship data under specific condition.
Hope it will be helpful for you. If you have any issue feel free to raise a ticket at https://bagisto.uvdesk.com/en/
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
1 comments