Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

laravel
php
communitycreator

How to add the Next and Previous link to a Post page in Laravel7

Chinweuba Elijah Azubuike

Introduction

The “next” and “previous” buttons make it easier to engage visitors in an application when the site is not paginated. In this shot, we add the “previous” and “next” links to our “post” page.

Step 1

We implement this method on the Post model, like so:


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();
    }
}

In the above code, we create two functions, the next and the previous function. In these functions, we do sorting of the queried result.

Step 2

Let’s add some code to our PostController for this purpose:

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

The above code basically implements the already created function, i.e., the next() and previous() functions from the model on a post query.

In Blade, you can add the $next and $prev functions in the following manner:

<a href="{{$next}}">Next</a> <a href="{{$prev}}">Previous</a> 

RELATED TAGS

laravel
php
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring