Laravel logo

Implementing AJAX Pagination in Laravel 10

Share this post on:

As web applications grow in complexity, providing a seamless user experience becomes
increasingly important. One key feature that enhances user experience is AJAX pagination. In
this tutorial, we’ll explore how to implement AJAX pagination in Laravel 10, leveraging the
power of the Laravel framework to create a smooth and responsive pagination system.

Why Use AJAX Pagination?

Traditional pagination reloads the entire page, which can be time-consuming and disrupt the user
experience. AJAX pagination, on the other hand, loads new data without refreshing the page,
making the application feel faster and more interactive. This is particularly useful for dynamic
web applications built with the Laravel framework.

Setting Up Laravel 10

Before we dive into AJAX pagination, ensure you have Laravel 10 installed. If not, you can
install it using Composer:

composer create-project --prefer-dist laravel/laravel laravel-ajax-pagination

Creating the Model and Migration

We’ll start by creating a model and migration for our data. For this example, let’s create a Post
model:

php artisan make:model Post -m

In the migration file, define the schema for the posts table:

Schema::create('posts', function (Blueprint $table) {
 $table->id();
 $table->string('title');
 $table->text('content');
 $table->timestamps();
});

Run the migration to create the table:

php artisan migrate

Seeding the Database

Next, we’ll seed the database with some sample data. Create a seeder for the Post model:

php artisan make:seeder PostSeeder
In the PostSeeder file, add the following code to generate dummy posts:
use App\Models\Post;
use Illuminate\Database\Seeder;
class PostSeeder extends Seeder
{
 public function run()
 {
 Post::factory()->count(100)->create();
 }
}

Now Generate PostFactory :

php artisan make:factory PostFactory –model=Post

Define the Factory:: Open the generated factory file located at
database/factories/PostFactory.php

<?php
namespace Database\Factories;
use App\Models\Post;
use Illuminate\Database\Eloquent\Factories\Factory;
class PostFactory extends Factory
{
 protected $model = Post::class;
 /**
 * Define the model's default state.
 *
 * @return array
 */
 public function definition()
 {
 return [
 'title' => $this->faker->sentence,
 'content' => $this->faker->paragraph,
 // Add other fields as necessary
 ];
 }
}

Run the seeder to populate the database:
php artisan db:seed –class=PostSeeder

Setting Up the Controller

Create a controller to handle the AJAX pagination logic:
php artisan make:controller PostController

In the PostController, add a method to fetch the paginated posts:

use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
 public function index(Request $request)
 {
 if ($request->ajax()) {
 $posts = Post::paginate(10);
 return view('posts.pagination', compact('posts'))->render();
 }
 $posts = Post::paginate(10);
 return view('posts.index', compact('posts'));
 }
}

Creating the Views

Create a view for displaying the posts and the pagination controls. In the
resources/views/posts directory, create two files: index.blade.php and
pagination.blade.php.

In index.blade.php:
<!DOCTYPE html>
<html>
<head>
 <title>Laravel 10 AJAX Pagination</title>
 <meta name="csrf-token" content="{{ csrf_token() }}">
 <link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
 <script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></scri
pt>
</head>
<body>
 <div class="container mt-5">
 <h2>Laravel 10 AJAX Pagination</h2>
 <div id="post-data">
 @include('posts.pagination')
</div>
 </div>
 <script type="text/javascript">
 $(document).ready(function() {
 $(document).on('click', '.pagination a', function(event) {
 event.preventDefault();
 var page = $(this).attr('href').split('page=')[1];
 fetch_data(page);
 });
 function fetch_data(page) {
 $.ajax({
 url: "/posts?page=" + page,
success: function(data) {
 $('#post-data').html(data);
 }
 });
 }
 });
 </script>
</body>
</html>
In pagination.blade.php:
<div class="table-responsive">
 <table class="table table-bordered">
 <thead>
 <tr>
 <th>Title</th>
 <th>Content</th>
 </tr>
 </thead>
 <tbody>
 @foreach ($posts as $post)
 <tr>
 <td>{{ $post->title }}</td>
<td>{{ $post->content }}</td>
 </tr>
 @endforeach
 </tbody>
 </table>
 {!! $posts->links() !!}
</div>

Route Definition:

In your routes/web.php file:
use App\Http\Controllers\PostController;
Route::get(‘/posts’, [PostController::class, ‘index’]);

Testing the AJAX Pagination

Start the Laravel development server:

php artisan serve

Navigate to http://127.0.0.1:8000/posts in your browser. You should see the paginated list
of posts with AJAX pagination working seamlessly

Conclusion

Implementing AJAX pagination in Laravel 10 is a great way to enhance the user experience of
your web application. By using the Laravel framework, you can easily create dynamic and
responsive pagination without refreshing the entire page. Whether you’re building a Laravel
CMS, a complex web application, or a simple blog, AJAX pagination can make your application
more interactive and user-friendly.

Remember to explore the vast ecosystem of Laravel packages and tools on Laravel GitHub to
further enhance your project. Stay tuned for more updates as Laravel 11 and new features like
Laravel Inertia and Livewire continue to evolve, making PHP and Laravel an even more
powerful combination for web development.

Happy coding with Laravel and PHP!