Laravel advanced search query fix

后端 未结 8 1303
终归单人心
终归单人心 2021-01-28 21:34

I have a search form with multiple input and select boxes I need help to get if conditions in my query in order to each part works separately and all at once.

he

8条回答
  •  鱼传尺愫
    2021-01-28 22:09

    it is very simple to make dynamic search by using treats we can use this for all models I made this dynamic as possible

    This is a trait that can be used by any models

    This function will remove code repetitions into your project

    public function scopeSearch($query, $keyword, $columns = [], $relativeTables = [])
    {
        if (empty($columns)) {
            $columns = array_except(
                Schema::getColumnListing($this->table), $this->guarded
            );
        }   
    
        $query->where(function ($query) use ($keyword, $columns) {
            foreach ($columns as $key => $column) {
                $clause = $key == 0 ? 'where' : 'orWhere';
                $query->$clause($column, "LIKE", "%$keyword%");
    
                if (!empty($relativeTables)) {
                    $this->filterByRelationship($query, $keyword, $relativeTables);
                }
            }
        });
    
        return $query;
    }
    

    Filter into relationship also

    private function filterByRelationship($query, $keyword, $relativeTables)
    {
        foreach ($relativeTables as $relationship => $relativeColumns) {
            $query->orWhereHas($relationship, function($relationQuery) use ($keyword, $relativeColumns) {
                foreach ($relativeColumns as $key => $column) {
                    $clause = $key == 0 ? 'where' : 'orWhere';
                    $relationQuery->$clause($column, "LIKE", "%$keyword%");
                }
            });
        }
    
        return $query;
    }
    

提交回复
热议问题