How to make previous & next links in laravel

How to make previous & next links in laravel

208

Today we will learn how to make Previous and Next links for our posts in laravel.

In this article we will learn:

Making previous & next links base on ID

Making previous & next links base on Slug


Let's begin

ADD BY POST ID

1. First thing we need is to make new controller we will call it BlogController

php artisan make:controller BlogController --resource

 

2. Open your BlogController and find show() method.

By default you have something like:

public function show($id)
{
  // 
}

Let load our post

//Dont forget to load posts model in Top of your controller
use AppPost;



public function show($id)
    {
        $post = Post::where('id', $id)->firstOrFail();
        return view('frontend.single', compact('post'));
    }

 

3. Don't forget to add Blogcontroller route in web.php

Route::resource('/blog', 'BlogController', ['except' => ['create', 'edit', 'update', 'destroy']]);

 

3.1 Getting URL

In case if you're wonder how to get your final URL for posts this is it:

{{$post->title}}

  4. Add Previous and Next links to our function

here is the code:

public function show($id)
    {
        $post = Post::where('id', $id)->firstOrFail();
        $previous = Post::where('id', '<', $post->id)->max('id');
        $next = Post::where('id', '>', $post->id)->min('id');
        return view('frontend.blog-post', compact('post', 'previous', 'next'));
    }

5. Now add your links in your blade file:



Prev	

Next

ADD BY POST SLUG

To using post slugs instead of post ids follow all the steps above and all you need to change is show() method, here is a sample of it:

public function show($slug)
    {
        $post = Post::where('slug', $slug)->firstOrFail();

        $previous = Post::where('slug', '<', $post->slug)->max('slug');
        $next = Post::where('slug', '>', $post->slug)->min('slug');
        return view('frontend.blog-post', compact('post', 'previous', 'next'));
    }

As you can see all we did was replacing all ID's with Slug and that was it! smile

Don't forget your show($id) has to change to show($slug) in order to work otherwise you'll get error.

- Last updated 4 years ago

Be the first to leave a comment.

You must login to leave a comment