简体   繁体   中英

I'm trying to use multiple filters on my database with laravel

I've tried implementing the multiple filters but each time I filter with respect to one it works but when filter with respect to the others the query only takes in one filter.

my Register controller:allCandidates

 public function allCandidates(){ $candidates = new Candidate; $queries = []; $columns = [ 'field', 'qualification', ]; foreach ($columns as $column) { if (request()->has($column)) { $candidates = $candidates->where($column, request($column)); $queries[$column] = request($column); } } if (request()->has('sort')) { $candidates =$candidates->orderBy('surname', request('sort')); $queries['sort'] = request('sort'); } $candidates =$candidates->paginate(10)->appends($queries); return view('contact.candidates', compact('candidates')); } 

Rewrite code as follows:

public function allCandidates(){

        $candidates = new Candidate;

        $columns = [
            'field', 'qualification',
        ];

        foreach ($columns as $column) {
            if (request()->has($column)) {
                $candidates->where($column, request($column));
            }
        }
        if (request()->has('sort')) {
            $candidates->orderBy('surname', request('sort'));
        }
        $candidates->paginate(10);
        return view('contact.candidates', compact('candidates'));
    }

Need not to reinitialize $candidates variable after once did. Just add filters or call another functions with the object $candidates.

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