How to Get Previous and Next Record in Laravel?

10-Mar-2023

.

Admin

Hi Guys,

In this example,I will learn you how to get previous and next record in laravel.you can easy and simply get previous and next record 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.

Get Next Record in Laravel


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 = User::where('id', '>', $user->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 = User::where('id', '<', $user->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 - Nicesnippets.com</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>

It will help you...

#Laravel 8

#Laravel 7

#Laravel

#Laravel 6