Laravel logo

200OK Solutions Blog | Insights & Tutorials

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!

Heer Patel

Strategy & Growth Manager

4+ years experience
Business growth specialist
Go-to-market strategist
SME & startup scaling
Cross-functional leadership

Core Expertise

Business Strategy 95%
Growth Marketing 92%
Sales Enablement 90%
Partnership Development 88%
  • Growth: Customer acquisition, revenue growth, market expansion
  • Marketing: Digital campaigns, brand positioning, lead generation
  • Business Development: Strategic partnerships, B2B relationships, client success
  • Operations: Process optimization, KPI tracking, business performance
  • Product Strategy: Market research, customer insights, go-to-market planning
  • Leadership: Cross-functional collaboration, stakeholder management, execution
  • Technology: SaaS, software products, digital transformation
  • Hospitality: Hotel technology & operational growth
  • Retail: Customer acquisition & omnichannel strategy
  • Professional Services: Business consulting & digital growth
  • SMEs: Scaling businesses through strategic planning
  • Developing data-driven growth strategies
  • Aligning marketing, sales, and operations
  • Building sustainable customer acquisition systems
  • Driving partnerships that create long-term value
  • Using analytics to optimize business performance
  • Focusing on scalable and measurable growth

Heer Patel is a Strategy & Growth Manager with extensive experience helping startups, SMEs, and technology businesses achieve sustainable growth through strategic planning, customer acquisition, and operational excellence.

He specializes in business strategy, go-to-market execution, growth marketing, and partnership development, working closely with leadership teams to identify new opportunities, optimize business processes, and accelerate revenue growth.

With a strong understanding of market dynamics, customer behavior, and digital transformation, He has successfully led cross-functional initiatives spanning marketing, sales, product, and operations. he is passionate about building scalable growth systems, strengthening client relationships, and helping businesses turn ambitious goals into measurable results through data-driven decision-making and strategic execution.

    Reach Out Us


    Your name

    Your email

    Subject

    Your message