i have a model User and i want search user by city but if the city varible is null a want all user
my code like this
User::where('city', $city)->orderBy('created_at')->paginate(10);
but if the city varible is null the query return nothing
i thy this
User::doesntHave('city')->get();
and this
User::whereHas('city')->get();
I know i can read my code like this
if($city){
User::where('city', $city)->orderBy('created_at')->paginate(10);
} else {
User::orderBy('created_at')->paginate(10);
}
but a want add other varible in my query and is not perfect
1. You could use where()
closure:
User::where(function ($q) use($city) {
if ($city) {
$q->where('city', $city);
}
})->orderBy('created_at')->paginate(10);
2. You could use when()
:
User::when($city, function ($q) use ($city) {
return $q->where('city', $city);
})->orderBy('created_at')->paginate(10);
3. Do this:
$users = User::orderBy('created_at');
if ($city) {
$users = $users->where('city', $city);
}
$users = $users->paginate(10);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With