ynoth25's avatar

Laravel Pagination and resource controller

I have a resource controller (index) that returns a paginated data, Is there a way where I can pass a parameter to the resource (index) as a filter for my query in the resource controller? current_url: http://127.0.0.1:8000/students?page=3

0 likes
14 replies
ynoth25's avatar

@bugsysha wait, how do I implement it in href tag? since pagination URL are auto generated. also the filter will come from the user

ynoth25's avatar

@SilenceBringer wait, how do I implement it in href tag? since pagination URL are auto generated. also the filter will come from the user

Snapey's avatar

suppose you paginate a list of users, and in the table of users you want that if someone clicks on the username column, then the results should be sorted by that column. You might have an a tag on the heading

    <a href="{{ route('users.index',['sort' => 'username']) }}

so this will load the index page on page 1 and pass it the sort querystring

all good so far, but when you go to page 2, the querystring is lost, so in the controller you need to use the pagination appends method to add the querystring back into the pagination urls

https://laravel.com/docs/8.x/pagination#appending-query-string-values

2 likes
ynoth25's avatar

thanks! @Snapey for additional info! by the way I'm using inertia js in my routes. like 'route('students.index', )

martinbean's avatar

@ynoth25 You can use something like Spatie’s query builder package to do the actual filtering in your index controller action.

To have the filters in the query string persist between pages, you can add withQueryString to the end of your paginate call:

$students = QueryBuilder::for(Student::query())
    ->allowedFilters([
        // Your allowed filters here...
    ])
    ->allowedSorts([
        // Your allowed sorts here...
    ])
    ->paginate()
    ->withQueryString();

// Return users in view

Now all of your pagination links (i.e. $students->links()) will contain any filtering or sorting values you add to the query string.

1 like
ynoth25's avatar

@martinbean wow! Thank you too!!! I'll try this one its short, readable and I will not use custom URL in href.

this is what I have currently: /students?approved=false and it works because pagination automatically attaches &page= page_number at the end of the URL.

martinbean's avatar

@ynoth25 Yeah, the withQueryString method will append any additional query string parameters other than page to your pagination URLs too.

Snapey's avatar

@ynoth25 What I explained is no different. You still have to pass the query string values in the first place

Please or to participate in this conversation.