Hello, laravel web developers! In this article, we'll see how to add datatable server side pagination in laravel 11. Here, we'll explore how to implement server-side pagination with Laravel 11 and jQuery. Server side pagination is typical as compared to fronted datatable pagination.
DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, and will add advanced interaction controls to any HTML table.
Laravel 11 Datatable Server Side Pagination with jQuery
We'll install the laravel 11 application using the following command in this step.
composer create-project laravel/laravel laravel-11-application
Next, we'll configure the database connection into the .env file.
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_11
DB_USERNAME=root
DB_PASSWORD=root
Then, we'll create a model and migration using the following command.
php artisan make:model Product -m
Migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('description');
$table->string('amount');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('products');
}
};
app/Model/Product.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
protected $guarded = [];
}
Then, migrate the table into the database using the following command.
php artisan migrate
Next, we'll create a Product Factory using the following command.
php artisan make:factory ProductFactory
database/factories/ProductFactory.php
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Product>
*/
class ProductFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->name(),
'description' =>fake()->sentence(),
'amount' => rand(1000, 9999)
];
}
}
Now, run the following command to create dummy records.
php artisan tinker
App\Models\Product::factory()->count(150)->create();
Then, we'll create a controller using the following command.
php artisan make:controller ProductController
app/Http/Controllers/ProductController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class ProductController extends Controller
{
public function index()
{
return view('products');
}
public function getProducts(Request $request){
// Page Length
$pageNumber = ( $request->start / $request->length )+1;
$pageLength = $request->length;
$skip = ($pageNumber-1) * $pageLength;
// Page Order
$orderColumnIndex = $request->order[0]['column'] ?? '0';
$orderBy = $request->order[0]['dir'] ?? 'desc';
// get data from products table
$query = \DB::table('products')->select('*');
// Search
$search = $request->search;
$query = $query->where(function($query) use ($search){
$query->orWhere('name', 'like', "%".$search."%");
$query->orWhere('description', 'like', "%".$search."%");
$query->orWhere('amount', 'like', "%".$search."%");
});
$orderByName = 'name';
switch($orderColumnIndex){
case '0':
$orderByName = 'name';
break;
case '1':
$orderByName = 'description';
break;
case '2':
$orderByName = 'amount';
break;
}
$query = $query->orderBy($orderByName, $orderBy);
$recordsFiltered = $recordsTotal = $query->count();
$users = $query->skip($skip)->take($pageLength)->get();
return response()->json(["draw"=> $request->draw, "recordsTotal"=> $recordsTotal, "recordsFiltered" => $recordsFiltered, 'data' => $users], 200);
}
}
Next, we'll define the routes into the web.php file.
use App\Http\Controllers\ProductController;
Route::get('/', [ProductController::class, 'index'])->name('home');
Route::post('/get-products', [ProductController::class, 'getProducts'])->name('getProducts');
Next, we'll create products.blade.php and add the product HTML table. Also, we'll utilize jQuery DataTables to handle the server-side pagination and search functionality.
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="csrf-token" content="{{ csrf_token() }}" />
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
<title>Laravel 11 Datatable Server Side Pagination - Techsolutionstuff</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-12 my-5">
<h3>Laravel 11 Datatable Server Side Pagination - Techsolutionstuff</h3>
</div>
<div class="col-12">
<table id="datatable" class="table" style="width:100%">
<thead class="table-dark">
<tr>
<td>Name</td>
<td>Description</td>
<td>Amount</td>
<td></td>
</tr>
</thead>
</table>
</div>
</div>
</div>
<!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) -->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js">
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js">
</script>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap4.min.js"></script>
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function() {
$('#datatable').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "{{ route('getProducts') }}",
type: "POST",
data: function (data) {
data.search = $('input[type="search"]').val();
}
},
order: ['1', 'DESC'],
pageLength: 10,
searching: true,
aoColumns: [
{
data: 'name',
},
{
data: 'description',
},
{
data: 'amount',
}
]
});
});
</script>
</body>
</html>
Now, run the laravel 11 application using the following command.
php artisan serve
You might also like: