Currently seeking new career opportunities in web development, particularly with Laravel, Hire Me

Laravel get previous and next record

David Carr

Laravel Framework Tutorials PHP & MySQL

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>

 

Laravel Modules Your Logo Your Logo Your Logo

Become a sponsor

Help support the blog so that I can continue creating new content!

Sponsor

My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Learn Laravel with Laracasts

Faster Laravel Hosting

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.