How to Create Ajax based Bootstrap Pagination in Laravel 9

Updated on ... 07th May 2023

This article focuses on creating AJAX pagination in Laravel 9, which can also be used in Laravel 8 and 10. AJAX pagination allows data to be loaded without a page refresh, which can save time and prevent the webpage from crashing when loading large amounts of data.

Using AJAX pagination, data can be loaded in chunks, making it more flexible and efficient than simple pagination, which requires the page to reload each time.

In this article, we will learn how to create jQuery AJAX pagination in Laravel 9 and explore various approaches to pagination in Laravel 8 and 9 using AJAX. This knowledge allows us to implement flexible and efficient pagination solutions for our Laravel projects.

How to Create  Ajax based Bootstrap Pagination in Laravel 9

We will follow these simple steps to create ajax based bootstrap 5 pagination in laravel:

  • Step 1: Install Laravel 9 Application
  • Step 2: Configure Database in .env file
  • Step 3: Create Model, controller, and seeder file using a single command
  • Step 4: Migrate the database and seed dummy data
  • Step 5: Create Route
  • Step 6: Create a Controller
  • Step 7: Create View
  • Step 8: Run Laravel 9 Application


Note: If you have already set up your laravel projects you can skip Step 1, Step  2, Step 3, and Step 4. else you can start from Step 1.

Step 1: Install Laravel 9 Application

we'll proceed with installing the Laravel 9 application using the command below:

composer create-project laravel/laravel ajax-pagination-app

Step 2: Configure Database in the .env file

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=ajax-pagination
DB_USERNAME=root
DB_PASSWORD=root

Step 3: Create Model, controller, and seeder file using a single command

php artisan make:model Post -msc

This single command will create three files Post.php model file inside the App\Models directory,  posts table migration file inside the database\migrations directory, and the PostSeeder.php file inside the database\seeder directory

Step 4: Migrate the database and seed dummy data

Now we will set up our dummy data in the seeder file PostSeeder.php:


                                                    

                                                    

                                                    <?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

use App\Models\Post;

class PostSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $num_users = 80;

        // Use a loop to create multiple users
        for ($i = 1; $i < $num_users; $i++) {
        Post::create([
            'title' => "Test title $i",
            'description' => "Lorem ipsum dolor sit amet consectetur adipisicing elit. Quod consequuntur vero facilis perspiciatis.",
          ]);
        }
    }
}

                                                    

                                                

Now Call it inside DatabaseSeeder.php


                                                    

                                                    

                                                    <?php
namespace Database\Seeders;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call([
            PostSeeder::class,
            //other seeder class
        ]);
    }
}

                                                    

                                                

You Should Also Read

Now run the Bellow command for migration and seeding the data:


                                                    

                                                    

                                                    //for migrating database
php artisan migrate

//for seeding the dummy data
php artisan db:seed

                                                    

                                                

Step 5: Create Route

Now open resource routes\web.php  and define route


                                                    

                                                    

                                                    <?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;

Route::get('/posts', [PostController::class,'index'])->name('posts.index');
Route::get('/posts/fetch_data', [PostController::class,'fetch_data'])->name('posts.fetch_data');

                                                    

                                                

Step 6: Create a Controller

We have already created our controller file in step 3, now we will define our function in it. open PostController.php form App\Http\Controllers\PostController.php and paste the bellow code:


                                                    

                                                    

                                                    <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Post;

class PostController extends Controller
{
    public function index()
    {
        $posts = Post::paginate(9);
        return view('posts.index', compact('posts'));
    }

    public function fetch_data(Request $request)
    {
        $posts = Post::paginate(9);

        if ($request->ajax()) {
            return view('posts.data', ['posts' => $posts])->render();
        }
    }
}

                                                    

                                                

Step 7: Create View

Now we will create two view file inside resources\views\posts\  I have divided my view file into two files one is index.blade.php and data.blade.php you can also create only one file index.blade.php

Now Create the data.blade.php file  in the resources/views folder


                                                    

                                                    

                                                    @foreach ($posts as $item)
    <div class="col-md-4 content_box">
        <div>
            <h2>{{ $item->title }}</h2>
            <p>{{ $item->description }}</p>
        </div>
    </div>
@endforeach

                                                    

                                                

Now open the index.blade.php file and paste the bellow code


                                                    

                                                    

                                                    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>How to Create Ajax based Bootstrap Pagination in Laravel 9</title>

    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
    <style>
        #items_container .content_box div {
            box-shadow: 0 0 3px rgba(0, 0, 0, .3);
            padding: 15px;
            margin-bottom: 20px;
        }
    </style>
</head>

<body>


    <div class="container py-4">
        <div class="row">
            <div class="col-md-12" id="items_container">
                <div class="row">
                    @include('posts.data')
                </div>
                <div class="col-md-12">
                    <div id="pagination_links">
                        {{ $posts->links('pagination::bootstrap-5') }}
                    </div>
                </div>
            </div>
        </div>
    </div>

<script src="https://code.jquery.com/jquery-3.6.4.min.js"
        integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script>
    <script>
        $(document).ready(function() {
            $(document).on('click', '#pagination_links a', function(e) {
                e.preventDefault();

                var url = $(this).attr('href');
                fetch_data(url);
            });
        });

        function fetch_data(url) {
            $.ajax({
                url: url,
                type: 'get',
                dataType: 'html',
                success: function(data) {
                    var $data = $(data);
                    var $filteredData = $data.find('#items_container').html();
                    $('#items_container').html($filteredData);

                    console.log($filteredData);

                    // $('#items_container').html(data);
                }
            });
        }
    </script>
</body>
</html>

                                                    

                                                
The script section at the bottom of the HTML document includes the jQuery library and a JavaScript code that sets up an event listener on the pagination links. When a pagination link is clicked, it prevents the default link behavior and sends an Ajax request to the URL of the clicked link.

The fetch_data function sends the Ajax request and specifies the URL, request type, and data type. When the request is successful, it receives the response data as an argument in the success callback function. The response data is wrapped in a jQuery object and filtered to get the content of the "#items_container"  div. The filtered content is then replaced inside the items_container div using the .html() method of the jQuery object.

Note that the best part of this tutorial is that all view data is returned, but the content inside the "#items_container" div is replaced after filtering so that the HTML header section, including the title and meta, will not be appended inside the div. This allows for cleaner and more efficient code.

Now run the command below to run the app:
php artisan serve

Now open http://127.0.0.1:8000/posts or http://localhost:8000/posts If you are using this code after downloading from here make sure to run the bellow command after downloading and before doing anything.


composer install

Related Post

Leave a comment