简体   繁体   English

如果Laravel中某些字段是可选的,则使用下拉列表过滤数据

[英]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. 当用户有10个下拉列表选择框来过滤数据时,我正在做一个项目。 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. 如何在输入选择查询中使用if条件。

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. 让我知道它是否有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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