Back

Laravel developers, friendly reminder: always put your orWhere queries carefully πŸ‘€

Always try to put them in a separate where πŸ‘Œ

2 β€’ β€’

195

β€’
  • No matching results...
  • Searching...

/ 1000

Man this can bite your ass pretty hard if you're not careful.

1 β€’ β€’

182

β€’

This will work correctly but if you want to add 3rd where which is not dependent with active status if it fails it still takes that entry as it has status active.

$users = User::query()
->where('role', 'admin')
->orWhere('status', 'active')
->get();

1 β€’ β€’

219

β€’

So if you add something like this..

$users = User::query()
->where('is_visible', true)
->where('role', 'admin')
->orWhere('status', 'active')
->get();

It will take hidden posts too if they have the active status 😬

1 β€’ β€’

175

β€’

The correct solution will be...

$users = User::query()
->where('is_visible', true)
->where(function (Builder $query) {
$query->where('role', 'admin')
->orWhere('status', 'active');
})
->get();

1 β€’ β€’

239

β€’

You can also use whereAny for Laravel 10.47+

β€’ β€’

108

β€’