How to the Get the Previous and Next Posts in Laravel
In this lesson, we will see how to get the previous and next posts in Laravel, sometimes when you get the post details you want to display the previous and the next posts as well.
Get the previous and next posts in Laravel
To do that inside your controller show method use the code below to get the previous and next posts and later inside your view template, you can use these variables.
$nextPost = Post::where('id', '>', $post->id)->min('id');
$previousPost = Post::where('id', '<', $post->id)->max('id');
$next = Post::find($nextPost);
$previous = Post::find($previousPost);
return view("posts.show")->with([ 'post' => $post, 'next' => $next, 'previous' => $previous]);