tuytoosh's avatar

use orWhere() in Eloquent

Hi all , I want to use orWhere() without using Query Builder and I want to return a collection... in Query Builder we have :

$users = DB::table('users')
                    ->where('votes', '>', 100)
                    ->orWhere('name', 'John')
                    ->get();

I want to grasp $users as a collection to paginate them with laravel pagination

for example we do not have this?

$user = App\User::all();
$newUsers = $user->where('votes', '>', 100)
                    ->orWhere('name', 'John')
                    ->get();
0 likes
6 replies
JarekTkaczyk's avatar

@tuytoosh

$users = App\User::all();
$newUsers = $users->filter(function ($user) {
    return $user->votes > 100 || $user->name == 'John';
});
4 likes
rdelorier's avatar

Seems pretty wasteful to grab all results and then filter them, who not just

App\User::where('votes', '>', 100)->orWhere('name', '=', 'John')->paginate(15);

Although I guess if you cant help it then Jareks answer should definitely work

3 likes
tuytoosh's avatar

@JarekTkaczyk . now I want to paginate the returned collection but I have this error :

FatalErrorException in userController.php line 35:
Call to undefined method Illuminate\Database\Eloquent\Collection::paginate()

without paginate it works good. I see in laravel API that filter() returns a collection and paginate() method used for collectios too , I do not know where is problem...

this is my code :

public function getCamps()
    {
        $user = Auth::user();

        //find user field camps
        $field_id = $user->field['id'];
        $field = App\Field::find($field_id);
        $camps = $field->camps()->get();

        //find active status camps
        $camps = $camps->where('status' , 0);

        //find user sex fields
        $newCamp = $camps->filter(function($camp)
        {
            $user_sex = Auth::user()->sex;
            return $camp->sex == 0 || $camp->sex == $user_sex;
        });
        $newCamp->paginate(10);
        $newCamp->setPath('camps');
        return view('user.camp.camps')
            ->with('camps' , $newCamp);

    }
JarekTkaczyk's avatar

@tuytoosh No, paginate is not collection method. You can paginate a collection manually.

I would simply use query builder and paginate on it.

tuytoosh's avatar

@JarekTkaczyk

in above example , I can do what? and why the error occurred?

i can paginate a collection like this : App\Camp::paginate(10)

but why i can not paginate $newCamp collection in above? is any difference between these?

JarekTkaczyk's avatar
Level 53

@tuytoosh

App\User::paginate(); // it's query mthod, returns collection

use query builder instead:

$camps = $field->camps()->where('status', 0)->where(function ($q) {
    $q->where('sex', Auth::user()->sex)->orWhere('sex', 0);
})->get();
8 likes

Please or to participate in this conversation.