Check Here
Check Here

Lazy Vs. Eager Loading in Laravel

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/

. . .

Comment (1)

Add Your Comment

  • Vivek
    Nice
  • Bagisto helped us in creating this full functional, professional and user friendly web app. Bagisto has lot to offer to the developer and the user. The framework is outstanding.

    Yosseph Baruch Dolgopolsky

    Yosseph Baruch Dolgopolsky

    allspot.store
    Talk to Sales

    Global

    Live Chat
    Start a Project

      Message Sent!

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

      Back to Home
      css.php