Laravel: dynamic where clause with Elouquent

前端 未结 6 1230
温柔的废话
温柔的废话 2021-02-05 03:44

I am calling URL with search params which are dynamic. How could I form proper Eloquent query?

In theory:

  1. query
  2. query whe
6条回答
  •  一整个雨季
    2021-02-05 04:27

    I came here from Google. If you are going to be iterating over more then 5 if statements, its more effective to use a switch statement

     if(empty($request->except('_token')))
            return 'false';
    
        $models = Vehicle::query();
        $request_query = $request->all();
        $year_switch = false;
    
        foreach ($request_query as $key => $field_value){
    
    
    
            if($field_value != 'any'){                
                switch($field_value){
                    case 'X':                                            
                    case 'Y':
                        $year_switch = true; 
                    break;
                    case'Z':
                        //Dynamic
                        $models->where($key,'LIKE', $field_value);
                    break;
    
                }                    
            }
        }
    

提交回复
热议问题