Get next and previous post link in Laravel

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


In view

<a href="{{ route( '', $next->id ) }}">{{$next->title}}</a>
<a href="{{ route( '', $previous->id ) }}">{{$previous->title}}</a>


Hi, I'm Saurav, the developer behind usingphp. Donate to help me keep usingphp free and maintained.

Please let me know what your thoughts or comments are on this article. If you have any suggestion or found any mistake in this article then please let us know.

Latest Comments

Add your comment