Laravel Get Next / Previous Record and Url - Yudhy Network

Share on:

Yudhy Network - Laravel get previous and next record. This tutorial shows simple and easy way to get previous and next record in laravel based application with example.

In this tutorial, we will learn how to get the next or previous record or data in laravel application.

Sometimes, when we work with a blog application in larvae. So at this time, we need to show the next or previous URL on posts. At that time we need to get the next record from the database table and the previous record from the database table.

Laravel Get Next and Previous Record and Url

Follow the below steps and get next or previous record or data from database table in laravel application.

1. Get previous record or data

We have one table name posts, we want to fetch previous record or data from the database table in laravel. So you can use the below eloquent query for that:

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

This laravel eloquent query is users where() and orderBy() methods to fetch previous records like title, URL, slug, etc from the database table in laravel

Recommended:- Laravel Where Multiple Condition

2. Get Next record or data

Get the next record or data from the database in the laravel app. We have one table name posts, we want to fetch the next record or data from the database table in laravel. So you can use the below eloquent query for that:

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

This laravel query is uses where(), first() and orderBy() to fetch next records from DB table.

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>

Please ask in the comments!

Suport : Cotekno.Com

comments powered by Disqus