Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Rymercyble's avatar

automatically changing query based on received data

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

0 likes
6 replies
Vilfago's avatar

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) ?

Vilfago's avatar

Assuming that the column "country" in your user table is the country id, try this :

class Country extends Model
{
    public function users()
    {
            return $this->hasMany(User::class, 'country');
    }   
}

and then :

Country::where('id', Request::get('country'))->with('users')->get();
arukomp's avatar
arukomp
Best Answer
Level 10
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();

Rymercyble's avatar

@arukomp how to change this

User::whereHas('languages', function($query){
                $query->where('name', Request::get('language'));
            })

to when(!empty... ? this relation is m:n with language_user pivot

arukomp's avatar

@Rymercyble just surround your existing whereHas query within a when

->when(!empty(Request::get('language')), function ($query) {
    $query->whereHas('languages', function ($query) {
        $query->where('name', Request::get('language'));
    });
})

Please or to participate in this conversation.