Summer sale! Save 50% on access to our entire library of courses.Join here →

How to get the next and previous records in Laravel

July 15th, 2024

Laravel doesn't have built-in support to fetch next and previous records, but adding a couple of helper methods to your model does the trick.

Let's look at how it works.

Let's imagine we have an article (like the one you're reading now), and you want to link to the next record. In your controller, whether you're using route model binding or not, it'll likely look like this:

$article = Article::find(1);

I'm using an ID here for simplicity.

And here's what we want to do!

$article = Article::find(1);
$article->next(); // Returns the next Article model

Once we've implemented the functionality to get the next and previous records, you can access this in your views directly or pass it down from your controller.

Over in your model, add next/previous functionality by creating two helper methods like this:

class Article extends Model
{
public function next()
{
return $this->orderBy('id')
->where('id', '>', $this->id)
->first();
}

public function previous()
{
return $this->orderByDesc('id')
->where('id', '<', $this->id)
->first();
}
}

Let's break this query down for the next method.

  1. Using the ID as the order (usually incrementing), use orderBy to get all articles in asc order.
  2. The where clause gets all records after the one you're working with
  3. Using first, we grab the first record from the list of records after the one we're working with (the next record!)

The same applies to the previous method, but in reverse (both in the ordering and the comparison operator).

With this in place, your next and previous helper methods will fetch your Eloquent models' next and previous records.

Some tips:

  1. If you're storing a specific order column on your models, use that instead of the ID.
  2. If there are no next/previous records, these methods will return null, so you can easily check if next/previous records exist.
  3. These are not eager loaded (and can't be), so if you're iterating over records and use either the next or previous methods, you'll be firing off an additional query for each record, causing an n+1 issue.
Thanks for reading! If you found this article helpful, you might enjoy our practical screencasts too.
Author
Alex Garrett-Smith
Share :

Comments

No comments, yet. Be the first to leave a comment.