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



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 App\Post;

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:

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


 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('', compact('post', 'previous', 'next'));

5. Now add your links in your blade file:

<a href="{{ URL::to( 'blog/' . $previous ) }}" class="prev">Prev</a>	

<a class="next" href="{{ URL::to( 'blog/' . $next ) }}">Next</a>




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('', 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.



Share this article: