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.
orderBy
to get all articles in asc
order.where
clause gets all records after the one you're working withfirst
, 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:
null
, so you can easily check if next/previous records exist.next
or previous
methods, you'll be firing off an additional query for each record, causing an n+1 issue.