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

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

Also Read: Send transactional email with Sendgrid 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

Also Read: Send transactional email with Sendgrid in Laravel

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

Close