Laravel 10 JQuery Ajax Pagination

Step 1 : Install Laravel Application

composer create-project laravel/laravel ajaxPagination-app

Step 2 : Database Configuration

.env 

DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

Step 3: Create Item Table and Model

In this step we have to create migration for items table using Laravel 5.4 php artisan command, so first fire bellow command: 

php artisan make:migration create_items_table

put bellow code in your migration file for create items table. path  database/migrations

<?php
    
    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;
        
    return new class extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up(): void
        {
            Schema::create('items', function ($table) {
                $table->id();
                $table->string('title');
                $table->string('description');
                $table->timestamps();
            });
        }
        
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down(): void
        {
            Schema::dropIfExists('items');
        }
    };

After create "items" table you should create Item model for items, so first create file in this path app/Models/Item.php and put bellow content in item.php file:

app/Models/Item.php

<?php
  
    namespace App\Models;
      
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\Model;
      
    class Item extends Model
    {
        use HasFactory;
    }

Step 4: Add New Route

In this is step we need to create routes for items listing. so open your routes/web.php file and add following route.

routes/web.php

<?php
  
    use Illuminate\Support\Facades\Route;
      
    use App\Http\Controllers\PaginationController;
      
    /*
    |--------------------------------------------------------------------------
    | Web Routes
    |--------------------------------------------------------------------------
    |
    | Here is where you can register web routes for your application. These
    | routes are loaded by the RouteServiceProvider within a group which
    | contains the "web" middleware group. Now create something great!
    |
    */
      
    Route::get('ajax-pagination', [PaginationController::class, 'index'])->name('ajax.pagination');

Step 5: Create Controller

app/Http/Controllers/PaginationController.php 

<?php
  
    namespace App\Http\Controllers;
      
    use Illuminate\Http\Request;
    use App\Models\Item;
    use Illuminate\View\View;
      
    class PaginationController extends Controller
    {
        /**
         * Write code on Method
         *
         * @return response()
         */
        public function index(Request $request): View
        {
            $items = Item::paginate(5);
      
            if ($request->ajax()) {
                return view('data', compact('items'));
            }
      
            return view('items',compact('items'));
        }
    }

Step 6: Create View

resources/views/items.blade.php 

<!DOCTYPE html>
    <html>
    <head>
        <title>Laravel 10 Ajax Pagination Example - webthestuff.com</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    </head>
    <body>
       
    <div class="container">
      
        <h2>Laravel 10 Ajax Pagination Example - webthestuff.com</h2>
      
        <div id="item-lists">
            @include('data')
        </div>
      
    </div>
      
    <script type="text/javascript">
      
    $(window).on('hashchange', function() {
        if (window.location.hash) {
            var page = window.location.hash.replace('#', '');
            if (page == Number.NaN || page <= 0) {
                return false;
            }else{
                getData(page);
            }
        }
    });
      
    $(document).ready(function()
    {
        $(document).on('click', '.pagination a',function(event)
        {
            $('li').removeClass('active');
            $(this).parent('li').addClass('active');
            event.preventDefault();
      
            var myurl = $(this).attr('href');
            var page=$(this).attr('href').split('page=')[1];
      
            getData(page);
        });
    });
      
    function getData(page){
        $.ajax({
            url: '?page=' + page,
            type: "get",
            datatype: "html",
        })
        .done(function(data){
            $("#item-lists").empty().html(data);
            location.hash = page;
        })
        .fail(function(jqXHR, ajaxOptions, thrownError){
              alert('No response from server');
        });
    }
      
    </script>
      
    </body>
    </html>

resources/views/data.blade.php

<table class="table table-bordered">
    <thead>
        <tr>
            <th>Title</th>
            <th>Description</th>          
        </tr>
    </thead>
    <tbody>
        @foreach ($items as $item)
        <tr>
            <td>{{ $item->title }}</td>
            <td>{{ $item->description }}</td>
        </tr>
        @endforeach
    </tbody>
    </table>
    
    
    {!! $items->render() !!}

Run Laravel App:

php artisan serve

Now, Go to your  browser, type the given URL and view the output:

http://localhost:8000/ajax-pagination