Lazy Vs. Eager Loading in Laravel

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:

 

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:

the query running behind that is:

select * from class where class.name' = ? limit 1
select * from
class where cities.name = ? limit 1
select * from
class 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.

 

Now all data in student and class in the relationship table will be load at same time.

Lazy & Eager Loading

In some case that is useful to eager loading dynamically, we can decide where  data in relationship table need to load.

 

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/

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


1 comments

  • Vivek
  • Start a Project




      Message Sent!

      If you have more details or questions, you can reply to the received confirmation email.

      Back to Home