This tutorial will cover DataTables Server-side Processing in CodeIgniter 4. You will learn how to use server-side DataTables in CodeIgniter to fetch data from a MySQL database through Ajax. Server-side processing ensures that an Ajax request is made for every table redraw, returning only the necessary data. This is particularly useful for large datasets, as demonstrated in this DataTables server side processing in CodeIgniter 4 example.
composer create-project codeigniter4/appstarter ci-4-datatable-app
Then, navigate to your project directory:
cd ci-4-datatable-app
# CI_ENVIRONMENT = production
CI_ENVIRONMENT = development
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=ci4_datatable
DB_USERNAME=root
DB_PASSWORD=
Download DataTables by either directly downloading the files or using a package manager like npm or CDN.
In your view file, add the following lines to include the DataTables library:
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/1.11.4/css/dataTables.bootstrap5.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/dataTables.bootstrap5.min.js"></script>
php spark make:controller UserController
In app/Controllers/UserController.php:
<?php
use App\Models\UserModel;
use CodeIgniter\Controller;
class UserController extends BaseController
{
public function index()
{
return view('users');
}
public function getUsers()
{
$model = new UserModel();
$request = \Config\Services::request();
$limit = $request->getPost('length');
$start = $request->getPost('start');
$order_column_value = $request->getPost('order')[0]['column'];
$order=$request->getPost('columns')[$order_column_value]['data'];
$dir = $request->getPost('order')[0]['dir'];
$totalData = $model->countAll();
$totalFiltered = $totalData;
if(empty($request->getPost('search')['value']))
{
$users = $model->orderBy($order, $dir)->findAll($limit, $start);
}
else {
$search = $request->getPost('search')['value'];
$users = $model->like('name', $search)->orLike('email', $search)->orderBy($order, $dir)->findAll($limit, $start);
$totalFiltered = $model->like('name', $search)->orLike('email', $search)->countAllResults();
}
$data = array();
if(!empty($users))
{
foreach ($users as $user)
{
$nestedData['id'] = $user['id'];
$nestedData['name'] = $user['name'];
$nestedData['email'] = $user['email'];
$nestedData['created_at'] = $user['created_at'];
$data[] = $nestedData;
}
}
$json_data = array(
"draw" => intval($request->getPost('draw')),
"recordsTotal" => intval($totalData),
"recordsFiltered" => intval($totalFiltered),
"data" => $data
);
return $this->response->setJSON($json_data);
}
}
?>
php spark make:model UserModel
Configure the UserModel:
<?php
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
protected $table = 'users';
protected $primaryKey = 'id';
protected $allowedFields = ['name', 'email', 'created_at','updated_at'];
}
Create a migration file to define the table structure:
php spark make:migration AddUser
Edit the migration file to define the table structure:
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddUser extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'BIGINT',
'constraint' => 255,
'unsigned' => true,
'auto_increment' => true
],
'name' => [
'type' => 'VARCHAR',
'constraint' => '255',
],
'email' => [
'type' => 'longtext'
],
'created_at' => [
'type' => 'TIMESTAMP',
'null' => true
],
'updated_at' => [
'type' => 'TIMESTAMP',
'null' => true
],
]);
$this->forge->addPrimaryKey('id');
$this->forge->createTable('users');
}
public function down()
{
$this->forge->dropTable('users');
}
}
Run the migration:
php spark migrate
php spark make:seeder UserSeeder
In app/Database/Seeds/UserSeeder.php:
<?php
namespace App\Database\Seeds;
use CodeIgniter\Database\Seeder;
use CodeIgniter\I18n\Time;
use App\Models\UserModel;
class UserSeeder extends Seeder
{
public function run()
{
$user = new UserModel;
$faker = \Faker\Factory::create();
for ($i = 0; $i < 100; $i++) {
$user->save(
[
'name' => $faker->name,
'email' => $faker->email,
'created_at' => Time::createFromTimestamp($faker->unixTime()),
'updated_at' => Time::now()
]
);
}
}
}
Run the seeder:
php spark db:seed UserSeeder
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DataTables with CodeIgniter 4</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/1.11.4/css/dataTables.bootstrap5.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/dataTables.bootstrap5.min.js"></script>
</head>
<body>
<div class="container">
<h1>User List</h1>
<table id="userTable" class="table table-bordered ">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Created At</th>
</tr>
</thead>
<tbody>
<!-- Data will be loaded here -->
</tbody>
</table>
</div>
<script>
$(document).ready(function() {
$('#userTable').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "<?php echo base_url('usercontroller/getusers'); ?>",
"type": "POST"
},
"columns": [
{ data: 'id' },
{ data: 'name' },
{ data: 'email' },
{ data: 'created_at' }
]
});
});
</script>
</body>
</html>
use CodeIgniter\Router\RouteCollection;
/**
* @var RouteCollection $routes
*/
$routes->get('/', 'Home::index');
$routes->get('users', 'UserController::index');
$routes->post('usercontroller/getusers', 'UserController::getUsers');
php spark serve
Visit
http://localhost:8080/users