How to Get Previous and Next Record in Laravel

To Get Previous and Next Record in Laravel; i am going to show you how to get the next or previous record or data with URL in laravel application.

When you want to put next and previous url button in a site. Which is built in Laravel Framework. Then this tutorial will help you. With which you can add Next and Previous button to your Laravel site, that too with url.

Laravel Get Previous and Next Record With URL

1. Get previous record or data

If you have posts table in your laravel app db, and want to fetch previous record or data from the database posts table in laravel app. So, use the following query for that:

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

2. Get Next record or data

Get the next record or data from the database in the laravel app. If you have table name posts, and want to fetch the next record or data from the database table in laravel. So use the following query for that:

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

Note: – To access data obtained from $next or $ previous variable. You can use it like this:

//id
 $previous->id
 //slug
 $previous->slug
 //id

 $next->id
 //slug
 $next->slug

Displaying the next and previous posts url. So you can show like this:

<div class="row">
    <div class="col-md-6">
        @if (isset($previous_record))
            <div class="alert alert-success">
            <a href="{{ url($previous_record->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_record->title }}</p>
                </div>
            </a>
            </div>
        @endif
    </div>
    <div class="col-md-6">
        @if (isset($next_record))
        <div class="alert alert-success">
        <a href="{{ url($next_record->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_record->title }}</p>
            </div>
        </a>
        </div>
        @endif
    </div>
</div>

Recommended Laravel Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.