Home Laravel Laravel React JS Pagination using Vite

Laravel React JS Pagination using Vite

by Shahriar Sagor

Today now in this example, I will teach you laravel react js pagination example. Here you can learn how to add pagination in react js laravel application. Now I would like to show you about laravel reactjs pagination. Then from here you will learn laravel inertia react pagination.

We can also use this example with any version laravel 6, laravel 7, laravel 8 and laravel 9.

Now In this tutorial, i will use laravel breeze, inertia js, vite, and tailwind CSS for create react js pagination with laravel API. Here i will also create “posts” table with title and body columns. then i will display all records with pagination.

So, let’s start and follow the below step to do react js pagination with laravel vite.

Step 1: Install Laravel

This part is optional; however, if you have not need created the laravel application, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Create Auth with Breeze

Now, in this step, i have to use the composer command to install the breeze. So let’s need to run the bellow command and install the bellow library.

composer require laravel/breeze --dev

now, we have to create the authentication by using the bellow command. We can also create the basic login, register and email verification by using react js. If you need to create team management then you have to pass the addition parameter. We can see this in the bellow commands:

npm install

let’s run the vite, we need to keep start by this command:

npm run dev

now, we have to run migration the command to create the database table:

php artisan migrate

Step 3: Create Migration and Model

Here, we have create the database migration for posts table and also we have to create model for posts table.

php artisan make:migration create_posts_table

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

now you have to create Post.php model by using the following command:

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'
    ];
}
Step 4: Create Route

Now in third step, we need to create one route for listing post with the pagination. So need to create one route here.

routes/web.php

<?php
 
use Illuminate\Foundation\Application;
use Illuminate\Support\Facades\Route;
use Inertia\Inertia;
use App\Http\Controllers\PostController;
  
/*
|--------------------------------------------------------------------------
| 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('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';

Step 5: Create Controller

Now in this step, i will create the PostController file and then add following code on 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
{
    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function index()
    {
        $posts = Post::latest()->paginate(1);
        return Inertia::render('Posts/Index', ['posts' => $posts]);
    }
}

Step 6: Create React Pages

Here, in this step i will create the react js file for Index.jsx and also Pagination.jsx component file.

so, let’s start and create it and then add the bellow code on 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 - Codingspoint.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>
    );
}

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>
        )
    );
}

Run Laravel App:

That’s good all the needed steps have been done, now we need to type the given below command and then hit enter for run the Laravel application:

php artisan serve

Also keep run the following command for vite:

npm run dev

If we want to build then we can also run the following command:

npm run build

Now, need to go our web browser, then type the given URL and view the application output:

http://localhost:8000

Read Also: php artisan serve not working in Laravel

Thanks for read. I hope it help you. For more you can follow us on facebook

close

You may also like