SpuriouslyAwake's avatar

Model::all() but return Eloquent Builder instead of Collection

Is there an equivalent of the all() scope that returns an instance of Eloquent Builder instead of Collection. I need to chain some queries together and end with pagination, like this:

$users = User::where('id','!=', 0); // not very beautiful

if($filterA){
    $users = $users->whereHas('thing');
}

if($filterB){
    $users = $users->where('other_thing', 'some_value');
}

$users->paginate(5);

I used a hacky solution to return an instance of Eloquent Builder that contains all the models. If I went with $users->User::all() the whereHas() and paginate() would fail.

Is there a more Laravel to achieve what I'm doing?

0 likes
6 replies
ricardoarg's avatar

you should do something like:

$users = User::where('id','!=', 0)
            ->when($filterA, function($query) {
                $query->whereHas('thing');
            })
            ->when($filterB, function($query) {
                $query->where('other_thing', 'some_value');
            })
            ->paginate(5);
vipin93's avatar

yes for paginate you can not use get() because it will give all record

Snapey's avatar

You can just initialise the model

This video from forum contributor saeed should help you exactly.

https://youtu.be/IcLaNHxGTrs?t=1m50s

Here I jumped direct to the refactor but of course you might find the whole thing interesting.

lem93's avatar
$builder = Model::query();
10 likes

Please or to participate in this conversation.