Home > Software engineering >  How to automatically call with() method on models during query?
How to automatically call with() method on models during query?

Time:11-03

I have a User Model and Country Model, and Country belongs to User.

I am getting users with country using User model with "with()" method, in different controllers & methods.

Users::with('country')->get();

in different controllers. I want

Users::get();

It should automatically call the with('country') even if I dont call it.

And if I call any other relation like:

User::with('role')->get()

Now it should get role and country both. Not just role.

How can I achieve this..?

CodePudding user response:

What you are looking for is called default eager loading

You can achieve this by adding a variable to your model called $with like so:

class User ... {
    protected $with = ['country'];
    ...
}

CodePudding user response:

add user's model

$with automatic added your realtionship


protected $with = ['country' , 'add some reation'];
  • Related