Thursday, December 26, 2024
Google search engine
HomeLanguagesLaravel Get Next and Previous URL and Record Tutorial

Laravel Get Next and Previous URL and Record Tutorial

To Get Previous and Next Record in Laravel; In this tutorial, you will learn how to get the next or previous record or data with URL 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.

How to Get Previous and Next Record, url in Laravel

Steps to get next and previous record or data, url 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

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>

Recommended Laravel Tutorials

RELATED ARTICLES

Most Popular

Recent Comments