I'd like to run different ->where() condition based to id.
Example what I'm trying to do:
I have joined activity table to interests table and based to ID I'd like to run different where condition.
->when('activity.id' <= '214469112', function ($q) { return $q->where('interests.type', 'regular'); }, function ($q) { return $q->where('activity.main', 1); })->get();However ->when() does not seem to respect <= => greater than or less than and returns always false so the return $q->where('activity.main', 1); is always used.
Any ideas how I could achieve different ->where() condition based to greater or less than with activity.id?
2 Answers
Laravel's ->when() method needs the first parameter to be true to run the first callback.
In the docs they determine the value of $role beforehand then pass it to the when() method.
` $role = $request->input('role'); $users = DB::table('users') ->when($role, function ($query) use ($role) { return $query->where('role_id', $role); }) ->get(); `You are trying to pass through a SQL expression as if it were a where clause which its not.
If you evaluate 'activity.id' <= '214469112' in artisan tinker it will return false which explains why the second callback is always being run.
In other words you are comparing a string ('activity.id') with a string ('214469112') which is the issue here.
I hope this helps!
1Sigh, sometimes one just tries to overcomplicate the problem.
Did this by using:
Where('id', '>', int)->where('condition1')->orWhere('id', '<=', int)->where('condition2')->get();