Implementing pagination in a Laravel and ReactJS application involves setting up pagination on the server side using Laravel and handling it on the client side using ReactJS. Here's a step-by-step guide:
Install Laravel: If you haven't already, create a new Laravel project using Composer:
bashcomposer create-project --prefer-dist laravel/laravel your-project-name
Create a Model and Migration: Create a model and migration for the data you want to paginate. For example:
bashphp artisan make:model Post -m
Run Migrations: Run the migrations to create the necessary database tables:
bashphp artisan migrate
Seed the Database (Optional): If you have data, you can seed the database with sample data:
bashphp artisan db:seed
Setup Routes and Controller:
Define routes in web.php
and create a controller for handling pagination:
php// routes/web.php
use App\Http\Controllers\PostController;
Route::get('/posts', [PostController::class, 'index']);
php// app/Http/Controllers/PostController.php
use App\Models\Post;
public function index()
{
$posts = Post::paginate(10); // Change 10 to the desired number of items per page
return response()->json($posts);
Install React: Set up a React application using Create React App or any other method you prefer.
bashnpx create-react-app your-react-app
Install Axios (or use Fetch): Install Axios to make HTTP requests from your React application:
bashnpm install axios
Create a Component: Create a React component to fetch and display paginated data. For example:
jsx// src/components/Posts.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const Posts = () => {
const [posts, setPosts] = useState([]);
const [currentPage, setCurrentPage] = useState(1);
useEffect(() => {
const fetchData = async () => {
const response = await axios.get(`/posts?page=${currentPage}`);
setPosts(response.data.data);
};
fetchData();
}, [currentPage]);
return (
<div>
{posts.map(post => (
<div key={post.id}>{post.title}</div>
))}
<button onClick={() => setCurrentPage(currentPage - 1)}>Prev</button>
<button onClick={() => setCurrentPage(currentPage + 1)}>Next</button>
</div>
);
};
export default Posts;
Use the Component:
Use the Posts
component in your main application file:
jsx// src/App.js
import React from 'react';
import Posts from './components/Posts';
function App() {
return (
<div className="App">
<h1>Posts</h1>
<Posts />
</div>
);
}
export default App;
Run the Application: Start your Laravel server and React development server:
bash// Laravel php artisan serve // React npm start
Open your browser and navigate to http://localhost:3000
to see the paginated posts.
This is a basic example, and you may need to customize it based on your specific requirements. Additionally, you might want to add error handling, loading indicators, and more advanced features depending on your application's needs.