简体   繁体   中英

Filter data using Dropdowns if some fields are optional in Laravel

I am working on a project when users have 10 dropdowns select box to filter data. The problem is that the user might not use all the select box. So I want to include some if conditions in this part.

public function PostSearch()
{
    $eye_color         = Input::get('eye_color');
    $tattoos           = Input::get('tattoos');
    $piercings         = Input::get('piercings');
    ....
    $user = User::where([['eye_color',$eye_color],
                            ['tattoos',$tattoos],
                            ['piercings',$piercings]])->get();
     return $user;
}

How to use if condition in the query for input select or not.

You can do something like this:

$filters = [
    'eye_color' => Input::get('eye_color'),
    'tattoos' => Input::get('tattoos'),
    'piercings' => Input::get('piercings'),
];

$user = User::where(function ($query) use ($filters) {
    if ($filters['eye_color']) {
        $query->where('eye_color', '=', $filters['eye_color']);
    }

    if ($filters['tattoos']) {
        $query->where('tattoos', '=', $filters['tattoos']);
    }

    if ($filters['piercings']) {
        $query->where('piercings', '=', $filters['piercings']);
    }
})->get();

return $user;

Let me know it's working or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM