Laravel Quick Tip – get previous / next records.

For one of my projects I needed to get an ID of the previous and next record in the DB.

Let’s say we are logged in as an admin and we are on this user’s page and we want to see next/previous user’s id.

The following Eloquent code makes it easy to do that:

// Get the current user that will be the origin of our operations
$currentUser = User::find(10);

// Get ID of a User whose autoincremented ID is less than the current user, but because some entries might have been deleted we need to get the max available ID of all entries whose ID is less than current user's
$previousUserID = User::where('id', '<', $currentUser->id)->max('id');

// Same for the next user's id as previous user's but in the other direction
$nextUserID = User::where('id', '>', $currentUser->id)->min('id');

This could go well with portfolios, orders, blog posts, all kinds of things where you need to display next/previous entry links.

Liked it? Take a second to support Maks Surguy on Patreon!
Become a patron at Patreon!

You may also like


Leave a comment