fcno's avatar
Level 6

Next and previous using paginate(1)

I have an index page with thousands of records (let's use the 'cars' model as an example). They are being displayed paginated.

On this index page, there is a link to the show page where the car is displayed in more detail.

On the show page there is a next and previous button to allow the user to navigate between the records without having to go back to the index.

However, calculating the next and previous requires unnecessary 'complexity' that could be circumvented using laravel's default pagination. Something like 'paginate(1)'.

The problem: how would I be able to set the exact pagination page (on the show page) based on the (car) link clicked by the user on the index page? That is, I have the car object and how do I find the next and the previous one using Laravel's default pagination strategy?

Thx for your help.

0 likes
8 replies
SilenceBringer's avatar

@fcno can you show an example how your url looks like (simple id/slug or record?)

Also - does you index page contains some filters and you want to apply all of this filters to next/prev too? like sorting order, and maybe filtering by some params

1 like
SilenceBringer's avatar

@fcno this way can suggest something like:

$nextId = Car::where('id', '>', $currentModel->id)->orderBy('id')->first()?->id;
$prevId = Car::where('id', '<', $currentModel->id)->latest('id')->first()?->id;
2 likes
fcno's avatar
Level 6

@SilenceBringer Hey man .. thx for the info. That's is how im doing rn. The problem with this approunch is that I'm felling the complexity is growing due to relationships involved in the sorting.

Thx for your help :)

Snapey's avatar

you can't do this with pagination

1 like
Tray2's avatar

One way is to always fetch the id:s of the one before and after the one you want to display, that way you can easily make next and previous links, Or you can use JavaScript to load the next and previous car.

1 like
jlrdw's avatar
jlrdw
Best Answer
Level 75

Also when going to that page you can calculate where it would be if paginate is 1. A simple count up to that record will give you the placement.

Then of course let this be a separate query.

1 like

Please or to participate in this conversation.