I guess you have two models, "Country" and "User" ?
and User hasOne Country, and Country hasMany User ?
Why don't you load all user based on the country specified (or all users if no country is specified) ?
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I want to make user filter search. For all users I can use
User::all();
And if i want to filter them by country I need
User::where('country', Country::where('name', $country)->select('id')->first()->id)
but this don't handle situation when user won't specify country so I need to change it to something like this
if (Request::get('country') == ''){
$country_e = '!=';
$country = 'default';
} else {
$country_e = '=';
}
User::where('country', $country_e, Country::where('name', $country)->select('id')->first()->id)
But this way I'm making pointless query so I can devide each combination which user can search in separated if and this way i would have to use like 100 ifs to handle every combination
So how to make query where "where" would count only if data which each "where" search was received
User::when(empty(Request::get('country')), function ($query) {
$query->where('country', '!=', Country::where('name', 'default')->value('id'));
})->when(!empty(Request::get('country')), function ($query) {
$query->where('country', '=', Country::where('name', Request::get('country')));
})->get();
Please or to participate in this conversation.