In this tutorial you will learn about the How to Get Previous and Next Record in Laravel and its application with practical example.
In this How to Get Previous and Next Record in Laravel Tutorial I will show you how to get the previous and next record in laravel. In this tutorial you will learn to get the previous and next record in laravel application. Working with any blog application in laravel we have to show the next or previous record in navigation. At that time we need to get the next or previous record from the database table.
How to Get Previous and Next Record in Laravel
In this step by step tutorial I’ll demonstrate you to get the next or previous record or data with URL in laravel. Please follow the instruction given below:
Get Next Record in Laravel
In laravel application next record can be accessed as following:
1 |
$next = Blog::where('id', '>', $blog->id)->orderBy('id')->first(); |
We have used the where(), first(), orderBy() likewise first() eloquent queries to get the next posts or records from the database.
Get Previous Record in Laravel
In laravel application previous record can be accessed as following:
1 |
$previous = Blog::where('id', '<', $blog->id)->orderBy('id','desc')->first(); |
We have used the where(), first(), orderBy() likewise first() eloquent queries to get the next posts or records from the database.
Access Prev / Next Records from Laravel Blade View
Below is example how to access previous and next records with url in blade view file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<!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> |