skip to Main Content

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..?

2

Answers


  1. 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'];
        ...
    }
    
    Login or Signup to reply.
  2. add user’s model

    $with automatic added your realtionship

    
    protected $with = ['country' , 'add some reation'];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search