nklvjvc's avatar

Collection orWhereIn

Hello, is there a way to use orWhereIn in collection. Method Illuminate\Database\Eloquent\Collection::orWhereIn does not exist. Since I have two two columns with _id and need to get data from both of them

->whereIn('fighter1_id', $following) Using whereIn works, but if I try to add another column ->whereIn('fighter2_id', $following) then it combines them and not show all results.

I need to something like this ->whereIn('fighter1_id', $following) ->orWhereIn('fighter2_id', $following)

0 likes
6 replies
krisi_gjika's avatar

are you sure you mean to call these methods on a collection and not on an eloquent builder?

nklvjvc's avatar

@krisi_gjika So I need whereIn and orWhereIn just to set condition on which results to display here

	$following = auth()->user()->follows()->pluck('id');
    return view('follows', [
        'fights' => Fight::all()
            ->sortByDesc('starts_at')
            ->where('result', '0')
            ->whereIn('fighter1_id', $following)
            ->WhereIn('fighter2_id', $following)
            ->take(10)
    ]);

so i want to achive of getting ->orWhereIn('fighter2_id', $following)

krisi_gjika's avatar

@nklvjvc try this:

$following = auth()->user()->follows()->pluck('id');
    
return view('follows', [
  'fights' => Fight::query()
    ->sortByDesc('starts_at')
    ->where('result', '0')
    ->where(function (Builder $query) use ($following) {
      $query->whereIn('fighter1_id', $following)
        ->orWhereIn('fighter2_id', $following)
    })
    ->limit(10)
    ->get()
]);
nklvjvc's avatar

@krisi_gjika It gives me: App\Http\Controllers\FollowController::App\Http\Controllers{closure}(): Argument #1 ($query) must be of type App\Http\Controllers\Builder, Illuminate\Database\Eloquent\Builder given on this line

->where(function (Builder $query) use ($following) {

Snapey's avatar

You have some good advice here (apart from spam by @lucas29 ). Make sure you understand;

        'fights' => Fight::all()
            ->sortByDesc('starts_at')
            ->where('result', '0')
            ->whereIn('fighter1_id', $following)
            ->WhereIn('fighter2_id', $following)
            ->take(10)

when you do this, everything after all() is working with a collection in memory and is not being applied to the database query.

Please or to participate in this conversation.