Reading this post will teach you how to add jQuery ajax pagination to a Laravel 11 application.
As you are aware, pagination is a fundamental need for any admin, ERP, or backend panel. By allowing us to load a small number of records each time, pagination helps us avoid having a broken webpage from too much data. It looks even more stunning if pagination is implemented with jQuery AJAX. AJAX pagination is incredibly useful since it loads only the data in your table rather than the entire page. I’ll be giving a very basic example of AJAX pagination in a Laravel application in this post.
In this example, we will make an items table and populate it with some fake information. After that, we’ll just provide a paginated list of every record. To obtain pagination data, jQuery AJAX code will be written.
Here, all you need to do is follow a few steps to start from scratch and develop a jQuery AJAX pagination example. So let’s do the following actions:
- Step 1: Install Laravel 11
- Step 2: Configuring the MySQL Database
- Step 3: Make a model and item table
- Step 4: Create Route
- Step 5: Create Controller
- Step 6: Create View File
- Launch the Laravel application:
Step 1: Install Laravel 11
Since we are beginning from scratch, the first thing we need to do is execute the command below to obtain a brand-new Laravel 11 version application. Thus, launch the command prompt or terminal and type the following:
composer create-project laravel/laravel projectName
Step 2: MySQL Database Configuration
The built-in SQLite database connection in Laravel 11 can be replaced with a MySQL connection by adding a new entry to the .env
file that contains the database name, username, and password.
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Step 3: Create Item Table and Model
Using the Laravel PHP Artisan command, we must make a migration for the items table in this phase. Hence, issue the following command first:
php artisan make:migration create_items_table
Following this operation, you will find a file in the database/migrations path. To construct the items table, you must insert the following code into your migration file.
<?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');
}
};
now, let’s run migration command:
php artisan migrate
You need make an item model for the items after making the “items” table. Consequently, first create a file called item.php under the path app/Models/Item.php and add the following content to it:
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;
protected $fillable = [
'title', 'description'
];
}
Step 4: Create Route
We must construct routes for item listings in this step. Hence, add the following route to your routes/web.php file by opening it.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PaginationController;
Route::get('ajax-pagination', [PaginationController::class, 'index'])->name('ajax.pagination');
Step 5: Create Controller
We need to generate two view files in this step: one for the layout and another for the data. Using the path app/Http/Controllers/PaginationController.php, we should now create a new controller named PaginationController. Put the following content in the controller file, as it will handle all listing items, item ajax calls, and return responses:
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
The final stage is to create the layout file items.blade.php (resources/views/items.blade.php), list all of the item codes here, and add the following code:
resources/views/items.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 11 Ajax Pagination Example - ItSolutionStuff.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">
<div class="card mt-5">
<h3 class="card-header p-3">Laravel 11 Ajax Pagination Example - ItSolutionStuff.com</h3>
<div class="card-body" id="item-lists">
@include('data')
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$(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).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->links('pagination::bootstrap-5') !!}
Run Laravel App:
After completing all the necessary steps, you must execute the command below and press Enter to launch the Laravel application:
php artisan serve
Now, Go to your web browser, type the given URL and view the app output:
http://localhost:8000/ajax-pagination