简体   繁体   中英

Laravel search results paginate without direct collection

I have a search like:

$users = User::search($q)
               ->orderBy($sortBy, $orderBy)
               ->paginate($perPage);

and I can paginate results in blade with

{{ $users->render() }}

no problem. However my SearchController continues like

if($request->loc){
    $users = $users->where('loc',$request->loc);
}
if($request->sz) {
    $users = $users->where('sz',$request->sz);
}
...
return view('search', compact('users'));

which means I cant use the {{ $users->render() }} in blade because $users doesnt have the orderBy, paginate of the collection.

How can I solve this? Thanks for answer!

You should not combine pagination and filtering the Collections, it can make the results flakey. If you want filtering with pagination you have to do it on the QueryBuilder .

For your logic you can utilize when($condition, $clojure) on the QueryBuilder that will only execute if the condition is true.

$users = User::search($q)
           ->orderBy($sortBy, $orderBy)
           ->when($request->loc, function ($query) use ($request) {
               $query->where('loc', $request->loc);
           })
           ->when($request->sz, function ($query) use ($request) {
               $query->where('sz', $request->sz);
           })
           ->paginate($perPage);

return view('search', compact('users'));

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