Laravel Pagination with jQuery Ajax Request

In this guide, I’m going to show you how to build pagination with Ajax in Laravel. You should have basic knowledge of jQuery and Ajax. So, let’s start:

Table of Contents

  1. Install Laravel and Basic Configurations
  2. Create Migration
  3. Create Controller
  4. Register Web Route
  5. Add Blade View Files
  6. The Output of The Project

Step 1 : Install Laravel and Basic Configurations

Each Laravel project needs this thing. That’s why I have written an article on this topic. Please see this part from here: Install Laravel and Basic Configurations.

Step 2 : Create Migration

We are going to create a migration file for books. We will store book data and will retrieve the data using Ajax pagination. Use this command to create the migration file:

php artisan make:migration create_books_table

After creating, open the books migration file from database/migrations folder and update the up() function:

timestamp_create_books_table.php
public function up()
{
    Schema::create('books', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->timestamps();
    });
}

Now migrate the migration using this command:

php artisan migrate

After successfully migration, insert some dummy data in the books table.

Step 3 : Create Controller

We need a controller to retrieve data from books table. Let’s create a controller using this artisan command:

php artisan make:controller BookController

Open the BookController from app\Http\Controllers folder and replace with code:

BookController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class BookController extends Controller
{
    public function books(Request $request)
    {
        $books = DB::table('books')->orderBy('id', 'DESC')->paginate(3);

        if ($request->ajax()) {
            return view('load_books_data', compact('books'));
        }
        return view('books', compact('books'));
    }
}}

In the book controller, we have called two views (blade files) named books and load_books_data. We will add these view files after a few steps.

Step 4 : Register Web Route

In this step, we will define a web route to connect to books() function of the book controller. Lets’ do this:

routes/web.php
Route::get('books', 'BookController@books');

Step 5 : Add Blade View Files

In step 3, we have called two views. We are going to add those two views in this step. Navigate to resources/views folder and create two files called books.blade.php and load_books_data.blade.php.

1.
Open books.blade.php and paste this code:

books.blade.php
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel Pagination with jQuery Ajax Request</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
<div class="container" style="max-width: 700px;">
    <div class="text-center" style="margin: 20px 0px 20px 0px;">
        <a href="https://shouts.dev/" target="_blank"><img src="https://i.imgur.com/hHZjfUq.png"></a><br>
        <span class="text-secondary">Laravel Pagination with jQuery Ajax Request</span>
    </div>

    @if (count($books) > 0)
        <section class="books">
            @include('load_books_data')
        </section>
    @else
        No data found :(
    @endif
</div>

<script type="text/javascript">
    $(function () {
        $('body').on('click', '.pagination a', function (e) {
            e.preventDefault();
            $('#load').append('<img style="position: absolute; left: 0; top: 0; z-index: 10000;" src="https://i.imgur.com/v3KWF05.gif />');
            var url = $(this).attr('href');
            window.history.pushState("", "", url);
            loadBooks(url);
        });

        function loadBooks(url) {
            $.ajax({
                url: url
            }).done(function (data) {
                $('.books').html(data);
            }).fail(function () {
                console.log("Failed to load data!");
            });
        }
    });
</script>
</body>
</html>

In the books.blade.php, we display books data from BooksController here:

@if (count($books) > 0)
    <section class="books">
        @include('load_books_data')
    </section>
@else
    No data found :(
@endif

And this is the Ajax part:

<script type="text/javascript">
    $(function () {
        $('body').on('click', '.pagination a', function (e) {
            e.preventDefault();
            $('#load').append('<img style="position: absolute; left: 0; top: 0; z-index: 10000;" src="https://i.imgur.com/v3KWF05.gif />');
            var url = $(this).attr('href');
            window.history.pushState("", "", url);
            loadBooks(url);
        });

        function loadBooks(url) {
            $.ajax({
                url: url
            }).done(function (data) {
                $('.books').html(data);
            }).fail(function () {
                console.log("Failed to load data!");
            });
        }
    });
</script>

2. Now open load_books_data.blade.php and paste this code:

load_books_data.blade.php
<div id="load" style="position: relative;">
    <table class="table table-bordered">
        <thead class="thead-light">
        <tr>
            <th scope="col">ID</th>
            <th scope="col">Book Name</th>
        </tr>
        </thead>
        <tbody>
        @foreach($books as $book)
            <tr>
                <td width="50px">
                {{$book->id}}</th>
                <td>{{$book->name }}</td>
            </tr>
        @endforeach
        </tbody>
    </table>
</div>

{!! $books->render() !!}

In this view, we render the pagination and book data. On Ajax request, this view is shown in books.blade.php.

Step 6 : The Output of The Project

Let’s run the project and see the output. Here’s my output:

The tutorial is over. You can download this project from GitHub. Thank you.


Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.