Get previous/next record IDs

Submitted by msurguy - 3 years ago

For one of my projects I needed to get an ID of the previous and next record in the DB. This could go well with portfolios, orders, blog posts, all kinds of things where you need to display next/previous entry links. 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. Enjoy!

// Get the current user that will be the reference point 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');

Ads cover the costs of maintaining Laravel-tricks

comments powered by Disqus

Ads cover the costs of maintaining Laravel-tricks