How to Get Previous and Next Record in Laravel

Last Updated on by in Laravel

Laravel get previous & next record, data, or url example. This tutorial will help us learn how to get the next / previous data or record in laravel application throughout this comprehensive tutorial.

A few days back, i got a task for my blogging site in which i needed to create a small feature where i needed to navigate to the next and previous post from the current page.

The goal was to create two buttons, previous and next, get the url of the post from the database table, set the post URL on the prev and next buttons, and enable the next and previous buttons pagination in the laravel application.

Laravel 9 Get Previous and Next Record or Data Example

Here are the quintessential steps you needed to follow to get next or previous data and records from the database table in the laravel.

Get Next Record in Laravel

I assume you have already created the blogs table and it has some post records. Now, below is the eloquent query that you can use to get the next record from the blogs database table.

As you can see, we have defined the where(), first(), orderBy() likewise first() eloquent queries to get the next posts or records from the database.

$next = Blog::where('id', '>', $blog->id)->orderBy('id')->first();

Get Previous Record in Laravel

Define the $previous variable, along with the Blog model. Set the where() clause, pass the id and blog id properties, and define the orderBy and first queries to fetch the previous records and post url or slug from the database.

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

Access Prev / Next Records from Laravel Blade View

Open the blade view template; you can get the idea from the below code example to show the previous and next blog posts with their respective slug and urls.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Laravel Fetch Previous and Next Record Example</title>

</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-6">
                @if (isset($previous))
                    <a href="{{ url($previous->url) }}">
                        <div> Previous</div>
                        <p>{{ $previous->title }}</p>
                    </a>
                @endif
            </div>

            <div class="col-6">
                @if (isset($next))
                    <a href="{{ url($next->url) }}">
                        <div>Next</div>
                        <p>{{ $next->title }}</p>
                    </a>
                @endif
            </div>
        </div>
    </div>
</body>

</html>

Conclusion

Finally, this quick tutorial is over. In this tutorial, you learned in the simple way how to fetch next and previous records with url in the laravel application.