Disable eager relations

17,166

Solution 1

If you have to set the $with property on your model rather than leaving it empty, you can manually override the relationships that need to be eager loaded like this:

Model::setEagerLoads([])->get();

Link to API for setEagerLoads

Solution 2

In addition to Thomas Kim answer.

If you anyway extend Eloquent\Model class and often need to strip off relations from model, this solution might suit you well.

  1. Create scope in your default model class:

    public function scopeNoEagerLoads($query){
        return $query->setEagerLoads([]);
    }
    
  2. For any ORM, that extends that class you will be able to:

    User::noEagerLoads()->all()
    

Solution 3

Just like the issues say

Model::without(['countries', 'roles' ])->all();
Share:
17,166

Related videos on Youtube

Yauheni Prakopchyk
Author by

Yauheni Prakopchyk

Updated on September 14, 2022

Comments

  • Yauheni Prakopchyk
    Yauheni Prakopchyk over 1 year

    In my project I have many Eloquent models that have eager relations configured in class like this:

    protected $with = [ 'countries', 'roles' ];
    

    But sometimes I need just old plain model without any relations. Can I somehow do:

    Model::noRelations()->all()
    

    Really don't wanna use query builder nor create another class just for few occasions.

  • Yauheni Prakopchyk
    Yauheni Prakopchyk over 8 years
    Works like a charm! Exactly what I need.
  • BlackBurn027
    BlackBurn027 over 6 years
    How can i implement this if This Model is being referred in relation of other Model something like ModelTwo::with('modelOne')->get(); how to avoid eager loading for modelOne then ?
  • Ahmed Aboud
    Ahmed Aboud about 3 years
    @BlackBurn027 i guess this should work ModelTwo::with(['modelOne' => function ($query) { $query->setEagerLoads([]); }]