Milind Daraniya

Laravel Get Next and Previous Record and URL Tutorial

Published September 9th, 2023 21 min read

In a Laravel application, there might be instances where you need to retrieve the next and previous records relative to a current record. Additionally, you may want to generate URLs to navigate to these records easily. In this tutorial, we'll guide you on how to achieve this functionality using Laravel's Eloquent ORM.

Step 1: Set Up the Database

For this tutorial, we'll assume you have a table named posts containing the records you want to navigate. This table should have an id column as the primary key for uniquely identifying each record.

Step 2: Create a Model

Create a model for the posts table using the following Artisan command:

php artisan make:model Post

Step 3: Define the Relationships

In your Post model, define relationships for getting the next and previous records. For this, we'll use the where clause with the > and < operators.

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    // Define the table name if different from 'posts'
    protected $table = 'posts';

    // Your other model code

    public function getNextPost()
    {
        return $this->where('id', '>', $this->id)->orderBy('id', 'asc')->first();
    }

    public function getPreviousPost()
    {
        return $this->where('id', '<', $this->id)->orderBy('id', 'desc')->first();
    }
}

Step 4: Create Routes and Controller

Create routes and a controller to handle displaying the next and previous records. For this example, we'll assume you have a PostController with an index method to display the posts.

use App\Http\Controllers\PostController;

Route::get('/posts', [PostController::class, 'index'])->name('posts.index');

Step 5: Implement the Controller Logic

In your PostController, implement the index method to fetch the current record and its next and previous records.

namespace App\Http\Controllers;

use App\Models\Post;

class PostController extends Controller
{
    public function index($id)
    {
        $post = Post::findOrFail($id);
        $nextPost = $post->getNextPost();
        $previousPost = $post->getPreviousPost();

        return view('posts.index', compact('post', 'nextPost', 'previousPost'));
    }
}

Step 6: Create the View

Create a view file (resources/views/posts/index.blade.php) to display the current record and links to navigate to the next and previous records.

<h1>{{ $post->title }}</h1>
<p>{{ $post->content }}</p>

@if ($previousPost)
    <a href="{{ route('posts.index', ['id' => $previousPost->id]) }}">Previous Post</a>
@endif

@if ($nextPost)
    <a href="{{ route('posts.index', ['id' => $nextPost->id]) }}">Next Post</a>
@endif

Step 7: Test the Functionality

Now, when you access the /posts/{id} route, you'll see the details of the current post, along with links to navigate to the next and previous posts.