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.
Here are the quintessential steps you needed to follow to get next or previous data and records from the database table in the 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();
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();
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>
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.
If you want to learn how to get the current route's name, component pathname or…
React show and hide example. In this tutorial, we will show you how to step…
Tabs are one of the best UI elements for displaying multiple contents in a single…
In this tutorial, we will learn how to create a toast notification component in the…
Bootstrap offers tons of custom UI solutions. On top of that, it is easy to…
React js counter using the useReducer hook example. In this post, we will learn how…