Avoid data leakage when using orWhere on a relationship

1$user->posts()
2 ->where('active', 1)
3 ->orWhere('votes', '>=', 100)
4 ->get();

Returns: ALL posts where votes are greater than or equal to 100 are returned

1select * from posts where user_id = ? and active = 1 or votes >= 100
1use Illuminate\Database\Eloquent\Builder;
2 
3$users->posts()
4 ->where(function (Builder $query) {
5 return $query->where('active', 1)
6 ->orWhere('votes', '>=', 100);
7 })
8 ->get();

Returns: Users posts where votes are greater than or equal to 100 are returned

1select * from posts where user_id = ? and (active = 1 or votes >= 100)

Tip given by @BonnickJosh

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord