Get next and previous post link in Laravel
Here I will show you how to display previous and next post link in single post page in laravel. For this we will use `max` and `min` functions in laravel. I'm using the following code to controller function to get next and previous post within a post.
public function post($id)
{
$post = Post::find($id);
$previous = Post::where('id', '<', $post->id)->max('id');
$next = Post::where('id', '>', $post->id)->min('id');
return view( 'post', compact( 'post', 'next', 'previous' ));
}
In Route file
Route::get('post/{id}','BlogController@post')->name('post.show');
In view
@if($next)
<a href="{{ route( 'blog.show', $next->id ) }}">{{$next->title}}</a>
@endif
@if($previous)
<a href="{{ route( 'blog.show', $previous->id ) }}">{{$previous->title}}</a>
@endif
Also Read: PHP script to add transparent logo on image
Here I will show you how to display previous and next post link in single post page in laravel. For this we will use `max` and `min` functions in laravel. I'm using the following code to controller function to get next and previous post within a post.
public function post($id)
{
$post = Post::find($id);
$previous = Post::where('id', '<', $post->id)->max('id');
$next = Post::where('id', '>', $post->id)->min('id');
return view( 'post', compact( 'post', 'next', 'previous' ));
}
In Route file
Route::get('post/{id}','BlogController@post')->name('post.show');
In view
@if($next)
<a href="{{ route( 'blog.show', $next->id ) }}">{{$next->title}}</a>
@endif
@if($previous)
<a href="{{ route( 'blog.show', $previous->id ) }}">{{$previous->title}}</a>
@endif
Also Read: PHP script to add transparent logo on image
Recommanded Articles
- How to create a multilevel category and subcategory in Laravel
- How to check YouTube video exist Laravel validation
- Multiple user roles authentication Laravel 8
- Deploy Laravel project from local to production server
- Make custom pagination URL in Laravel without query strings
- Web Scraping in Laravel using Goutte
- Insert values during migration run laravel
- Validation for string characters only with custom message in Laravel
- Add new columns in a table Laravel
- How to create foreign key constraints in Laravel
Latest Comments