Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Laravel next previous post button livewire example

How to get the Next Previous record in Laravel Livewire?

I will provide you with an example of the next previous post button using the model attribute in the Laravel Livewire application.


How to get the Next Previous record in Laravel Livewire?

get the Next Previous record in Livewire

check next or previous record in livewire laravel

Laravel next previous post button livewire example

The need for next, and previous records in any application on clicking with button, needs in eCommerce, blog post application, to check next or previous record or item using clicking on the button or an arrow link to create a more user-friendly application.

Okay, let’s get straight to the steps for Getting the next previous record in the Laravel livewire application with an Example 👇

Generate migration with model

php artisan make:model Blog -m

Update Migration

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('blogs', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('image');
            $table->text('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('blogs');
    }
};

Run Migration

php artisan migrate
create blog post migration

Defining Model Factories – Generating Factories

php artisan make:factory BlogFactory

database\factories\BlogFactory.php

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Blog>
 */
class BlogFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition()
    {
       return [
            'title' => $this->faker->sentence(),
            'image' => $this->faker->imageUrl(640,480),
            'description' => $this->faker->text(),
        ];
    }
}

Define Factory in Database Seeder Trait

database\seeders\DatabaseSeeder.php

<?php

namespace Database\Seeders;

// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {

        // $this->call(CountrySeeder::class);
         \App\Models\Blog::factory(10)->create();
       
    }
}

Seed the database

php artisan db:seed
insert records using faker

Related article:- Generate a unique mobile phone number with Faker in Laravel.

Create a Livewire Component

Okay, next we need to create a Livewire component to get the Next Previous record using Livewire. Please run the artisan command as above. From this command, it will generate two files located in the directory as below.

php artisan make:livewire NextPrevRecordExample
CLASS: app/Http/Livewire/NextPrevRecordExample.php
VIEW:  resources/views/livewire/next-prev-record-example

routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Livewire\NextPrevRecordExample;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/


Route::get('/blog/{id?}',NextPrevRecordExample::class)->name('blog.post');

Update the Model and add the Attribute

use\App\Models\Blog.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Blog extends Model
{
    use HasFactory;
 
   #Get previous and next post records
   public function getNextAttribute(){
    return static::where('id', '>', $this->id)->orderBy('id','asc')->first();
   }

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

app/Http/Livewire/NextPrevRecordExample.php

<?php

namespace App\Http\Livewire;

use App\Models\Blog;
use Livewire\Component;

class NextPrevRecordExample extends Component
{
    public function mount($id)
    {
        $post = Blog::where('id',$id)->first();
        if($post){
        $this->post = $post;
        }else{
            abort(404);
        }
    }

    public function render()
    {
        $post = Blog::first();
        return view('livewire.next-prev-record-example',['post' => $post])->extends('layouts.app');
    }
}

resources/views/livewire/next-prev-record-example.php

<div>

            <div class="box">
               <div class="content">
                  <h1>{{ $post->title }}</h1>
                  <p>{{ $post->description }}</p>
               </div>
               <div class="PrevNext">
                  @if (isset($post->previous))
                  <a href="{{ route('blog.post',$post->previous->id)}}">‹ Previous</a>
                  @endif
                  @if (isset($post->next))
                  <a href="{{ route('blog.post',$post->next->id) }}">Next ›</a>
                  @endif
               </div>
            </div>
         
</div>

I hope that this article helped you learn how to get the Next Previous record in Laravel Livewire. You may also want to check out our guide on How to create dynamic input fields with Laravel Livewire.