How to get Next Previous Records in Laravel7.x with Example

1415 views 2 years ago Laravel

We all ken that, Laravel is propagating day by day. Have you endeavored to engender a blog cms in Laravel? If affirmative, might be you have faced quandary to get next and precedent post.
Getting next and anterior post is very facile in Laravel. Let’s start.
At first integrate 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();
        // write here you return blade login...
     }
)

In blade,

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

i hope you like this article.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]