adding reactjs pagination in laravel 9 vite
Laramatic.com

React Pagination Laravel 9 with Vite Tutorial Walkthrough

This tutorial is about react pagination Laravel 9 with vite and you will learn how to add reactJS pagination in our laravel 9 with simple steps. 

Requirements 

  • Laravel Breeze
  • Inertia JS
  • Vite 
  • Tailwind CSS

We will create

  • Posts Table
  • Post Titles 
  • Columns 

We will create reactjs pagination with the help of Laravel 9 API using laravel breeze, vite, inertia js and tailwind CSS. We will use all of these to create post examples with respective titles and columns to show records and their pagination. 

Steps to create pagination in Laravel 9 reactjs with vite:

#1 Install Laravel 9 or Create a New Project  

Install Laravel 9 app or create a new laravel project if you have not it already in your terminal use this command:

composer create-project laravel/laravel^9 reactjs-pagination-laravel-vite

#2 Create Auth Using Laravel Breeze

We have to use the global composer command and install Laravel breeze library by using this command: 

composer require laravel/breeze --dev

Next we need to create the basic register, login and email verification rules for our app using reactjs. To do that use this command in your terminal:

php artisan breeze:install react

Next let’s install NodeJS package manager 

npm install

Run database migration command in your terminal

php artisan migrate

This will create a new database table for you.

#3 Database Migration Model

Now migrate or create database migration and model for our posts. First create posts table

php artisan make:migration create_posts_table

Let’s migrate now use this code piece

<?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('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    } 
}php artisan migrate

Let’s use following command to create our model Post.php:

php artisan make:model Post

App/Models/Post.php

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Post extends Model
{
    use HasFactory;
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'title', 'body'
    ];
}

#4 Adding Route

We need to add Route for posts listing with pagination. Type this command to create a route:

routes/web.php

<?php
 
use Illuminate\Foundation\Application;
use Illuminate\Support\Facades\Route;
use Inertia\Inertia;
use App\Http\Controllers\PostController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here we can register our web routes for our app and you can too for the same reason. They
| get loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. 
|
*/
   
Route::get('posts', [PostController::class, 'index'])->name('posts.index');
   
Route::get('/', function () {
    return Inertia::render('Welcome', [
        'canLogin' => Route::has('login'),
        'canRegister' => Route::has('register'),
        'laravelVersion' => Application::VERSION,
        'phpVersion' => PHP_VERSION,
    ]);
});
    
Route::get('/dashboard', function () {
    return Inertia::render('Dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');
   
require __DIR__.'/auth.php';

The above code piece will create router for our app.

#5 Create Post Controller

Next we are suppsose to create our PostController file and include this code in it.

app/Http/Controllers/PostController.php

<?php
    
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use Inertia\Inertia;
use App\Models\Post;
    
class PostController extends Controller
{
    /**
     * Display form for our new resource.
     *
     * @return Response
     */
    public function index()
    {
        $posts = Post::latest()->paginate(1);
        return Inertia::render('Posts/Index', ['posts' => $posts]);
    }
}

Since until now we have database model post lists, router added and post controller the next two steps will do finish the job. The first starts by creating React Pages for our app.

#6 React Pages

Now we are creating react js file for Index.jsx and Pagination.jsx component file. Once created we will add this code
in it resources/js/pages/posts/index.jsx

import React from 'react';
import Authenticated from '@/Layouts/Authenticated';
import { Inertia } from "@inertiajs/inertia";
import { Head, usePage, Link } from '@inertiajs/inertia-react';
import Pagination from '@/Components/Pagination';
  
export default function Dashboard(props) {
    const { posts } = usePage().props
  
    return (
        <Authenticated
            auth={props.auth}
            errors={props.errors}
            header={<h2 className="font-semibold text-xl text-gray-800 leading-tight">Posts</h2>}
        >
            <Head title="Laravel 9 React JS Pagination Example with Vite - ItSolutionStuff.com" />
  
            <div className="py-12">
                <div className="max-w-7xl mx-auto sm:px-6 lg:px-8">
                    <div className="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                        <div className="p-6 bg-white border-b border-gray-200">
  
                            <table className="table-fixed w-full">
                                <thead>
                                    <tr className="bg-gray-100">
                                        <th className="px-4 py-2 w-20">No.</th>
                                        <th className="px-4 py-2">Title</th>
                                        <th className="px-4 py-2">Body</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {posts.data.map(({ id, title, body }) => (
                                        <tr>
                                            <td className="border px-4 py-2">{ id }</td>
                                            <td className="border px-4 py-2">{ title }</td>
                                            <td className="border px-4 py-2">{ body }</td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
  
                            <Pagination class="mt-6" links={posts.links} />
  
                        </div>
                    </div>
                </div>
            </div>
        </Authenticated>
    );
}

Now resources/js/Components/Pagination.jsx

import React from 'react';
import { Link } from '@inertiajs/inertia-react';
  
export default function Pagination({ links }) {
  
    function getClassName(active) {
        if(active) {
            return "mr-1 mb-1 px-4 py-3 text-sm leading-4 border rounded hover:bg-white focus:border-primary focus:text-primary bg-blue-700 text-white";
        } else{
            return "mr-1 mb-1 px-4 py-3 text-sm leading-4 border rounded hover:bg-white focus:border-primary focus:text-primary";
        }
    }
  
    return (
        links.length > 3 && (
            <div className="mb-4">
                <div className="flex flex-wrap mt-8">
                    {links.map((link, key) => (
                            link.url === null ?
                                    (<div
                                            className="mr-1 mb-1 px-4 py-3 text-sm leading-4 text-gray-400 border rounded"
                                        >{link.label}</div>) :
  
                                    (<Link
                                                className={getClassName(link.active)}
                                                href={ link.url }
                                            >{link.label}</Link>)
                                    ))}
                </div>
            </div>
        )
    );
}

#7 Let’s Run Our Laravel App Project

We are almost done, just this command to test our Laravel project app

php artisan serve

Also run this for vite:

npm run dev

For start creating and building use this command in your terminal

npm run build

We also need to create some more posts to keep it testing at our end. So that was it, about using react pagination in Laravel 9 with vite. Let us know in the comments if you encounter any errors.