22

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
  • 10,202
  • 4
  • 33
  • 37

3 Answers3

60

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

Thomas Kim
  • 15,326
  • 2
  • 52
  • 42
  • Works like a charm! Exactly what I need. – Yauheni Prakopchyk Dec 02 '15 at 21:10
  • 4
    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 ? – BlackBurn027 Sep 25 '17 at 05:49
  • 1
    @BlackBurn027 i guess this should work ModelTwo::with(['modelOne' => function ($query) { $query->setEagerLoads([]); }] – Ahmed Aboud Feb 01 '21 at 10:09
  • https://laravel.com/api/5.1/Illuminate/Database/Eloquent/Builder.html#method_setEagerLoads returns 404 @Thomas Kim – sh1hab May 23 '22 at 18:45
  • still works for laravel 9 https://laravel.com/api/9.x/Illuminate/Database/Eloquent/Builder.html#method_setEagerLoads – Stetzon Jan 18 '23 at 17:34
18

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()
    
Yauheni Prakopchyk
  • 10,202
  • 4
  • 33
  • 37
8

Just like the issues say

Model::without(['countries', 'roles' ])->all();
nick huang
  • 131
  • 1
  • 6