Alzaabi98's avatar

pagination with filtering - issue in pagination goes back to unfiltered data

Hi all,

I want to show all records in index.blade.php, at the same time I wan to allow users to filter results based in certain criteria such as country etc.

I was able to implement filter and pagination but I have once issue :

When the user filter something , pagination does not pick the filtered result except in page #1. Then it will go back to unfiltered data,

here is the code in controller

    public function index(Request $request) {
        
        if ($request->has('country') ) {
            
            $members = Member::where('country',$request->country)->paginate(5);
        
        } else {
            
            $members = Member::paginate(8) ;
        }
        
        
        return view('members.index', compact('members'));
    }

in index.blade.php .. the code to send filtered info is :


form method="get" action="/members">

    <input type="checkbox" name="country" value="Oman"/> Oman <br>
    
    <input type="submit" class="btn btn-default" value="Filter">

 </form>

please advice how can I keep the pagination linked to filtered data

0 likes
6 replies
vipin93's avatar

{{ $members->appends(request()->only(['country']))->links() }}

sylar's avatar
$members->appends(Request::except('page'))->links()
Alzaabi98's avatar

thanks vipin and sylar, both works..

but what is the diff.

I wonder if this will work also i have more filtered data .. for example.. user can filter country,, region..state.. will this work as well.

vipin93's avatar
vipin93
Best Answer
Level 13

{{ $members->appends(request()->only(['country','state','region'.....]))->links() }}

sylar's avatar

except - blacklist, append all params except page

only - whitelist, append only specified params

For me, a close analogy is $fillable and $guarded properties in Eloquent Model.

1 like
Alzaabi98's avatar

thank you both of you .. i would like to give both right answer but i could not .. :)

thanks for your prompt answer.

Please or to participate in this conversation.