In this tutorial, we will learn How to Get Previous and Next Record in Laravel



Get Next Record in Laravel

$next = User::where('id', '>', $user->id)->orderBy('id')->first();

Get Previous Record in Laravel

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

Access Prev / Next Records from Laravel Blade View

<!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 - rathorji.in</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->name }}</p>
                    </a>
                @endif
            </div>

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

</html>


May this example help you.