Laravel Next and Previous Post

Rakibul Islam
1 min readMay 23, 2020

We all know that, Laravel is getting popular day by day. Have you tried to create a blog cms in Laravel? If yes, might be you have faced problem to get next and previous post.

Getting next and previous post is very easy in Laravel. Let’s start.

At first add this two method in you Post model,

class Post extends Model
{
……………………………………. public function next()
{
return $this->where(‘id’, ‘>’, $this->id)->orderBy(‘id’,’asc’)->first();
}
public function previous()
{
return $this->where(‘id’, ‘<’, $this->id)->orderBy(‘id’,’desc’)->first();
}}

Then you can call next() and previous() any where from post object

In Controller,

class PostController extends Controller
{
public function show($slug, Post $post)
{
$post = $post->where('slug',$slug)->first();
$next = $post->next();
$prev = $post->previous();
.............................
}
)

In blade,

$next = $post->next();
$prev = $post->previous();

Happy coding.

--

--

Rakibul Islam

Passionate PHP Expert, Love to make things that make a difference! You can find me here, https://www.linkedin.com/in/rakibhstu/