Loading...

Laravel get previous and next record

David Carr

2 min read - 1st Jan, 2018

A really common task is to display links for the previous and next record typically you find these on blogs, when viewing the post a previous title and link is displayed and the same for the next post, as long as they are previous and next posts. In this post, I'll explain how to create these.

First get a record out of the database:

$post = Post::where('slug', $slug)->firstOrFail();

Now with a database record, we can get the previous record where the record id is less than the id stored inside $post order by the id in descending order and use first() to get a single record back, optionally you can add a pluck() or select() calls to restrict the data coming back.

$previous = Post::where('id', '<', $post->id)->orderBy('id','desc')->first();

To get any attribute pout of $previous you could call it like this:

//id
$previous->id

//title
$previous->title

To get the next record it's almost the same query, this time get the record where the id is more than the id stored in $post.

$next = Post::where('id', '>', $post->id)->orderBy('id')->first();

Both $previous and $next should be passed to the view.

When displaying them a check should be made to ensure the $previous or $next exists, here's an example:

<div class="row">
    <div class="col-md-6">

        @if (isset($previous))
            <div class="alert alert-success">
            <a href="{{ url($previous->slug) }}">
                <div class="btn-content">
                    <div class="btn-content-title"><i class="fa fa-arrow-left"></i> Previous Post</div>
                    <p class="btn-content-subtitle">{{ $previous->title }}</p>
                </div>
            </a>
            </div>
        @endif
    </div>
    <div class="col-md-6">

        @if (isset($next))
        <div class="alert alert-success">
        <a href="{{ url($next->slug) }}">
            <div class="btn-content">
                <div class="btn-content-title">Next Post <i class="fa fa-arrow-right"></i></div>
                <p class="btn-content-subtitle">{{ $next->title }}</p>
            </div>
        </a>
        </div>
        @endif
    </div>
</div>

 

0 comments
Add a comment