In this tutorial you will learn about the Laravel Get Next and Previous Record and Url Tutorial and its application with practical example.
In this Laravel Get Next and Previous Record and Url Tutorial I will show you how to get the next or previous record or data with URL in laravel application. In this tutorial you will learn to get the next or previous record or data with URL in laravel application. Working with any blog application in laravel we have 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. In this step by step tutorial I’ll demonstrate you to get the next or previous record or data with URL in laravel.
Laravel Get Next and Previous Record and Url Tutorial
1. Get previous record or data
We can access the previous record as following:
1 |
$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
We can access the next record as following:
1 |
$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:
1 2 3 4 5 6 7 8 9 |
//id $previous->id //slug $previous->slug //id $next->id //slug $next->slug |
You can display the next and previous posts url as following:
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 |
<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> |