CodeIgniter 4 Server Side DataTable Tutorial

Apr 21, 2022 . Admin



Hi Guys,

Today, I will let you know example of codeigniter 4 server side datatable tutorial. if you have question about how to implement and use datatables in codeigniter 4 then I will give simple example with solution. I explained simply step by step codeigniter 4 datatables tutorial. This article will give you simple example of yajra datatables codeigniter 4 example. Follow bellow tutorial step of codeigniter 4 datatables example.

In this tutorial,I will learn you how to implement and use datatables in codeigniter 4.you can easy and simply implement and use datatables in codeigniter 4.

So Basically Datatables is a widely used and most popular JavaScript library to display data in a tabular form. It lets you add advanced interaction controls to your HTML tables and comes with built-in functionalities such as Data Sorting, Searching, Pagination, and Filtering.

Step 1: Install Codeigniter 4

First of all if you have not created the codeigniter app, then you may go ahead and execute the below command:

composer create-project codeigniter4/appstarter ci-news
Step 2: Display Errors in Codeigniter

This step explains how to enable the error reporting in Codeigniter and shows errors in debugging the app in real-time.

Go to app/Config/Boot/development.php file and set the display_errors to 1 instead of 0. Perform the same process in app/Config/Boot/production.php file as well.

ini_set('display_errors', '1');
Step 3: Configure Database Connection

add your database name, username and password in application/config/database.php file and establish the database connection.

public $default = [
    'DSN'      => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'demo',
    'DBDriver' => 'MySQLi',
    'DBPrefix' => '',
    'pConnect' => false,
    'DBDebug'  => (ENVIRONMENT !== 'production'),
    'cacheOn'  => false,
    'cacheDir' => '',
    'charset'  => 'utf8',
    'DBCollat' => 'utf8_general_ci',
    'swapPre'  => '',
    'encrypt'  => false,
    'compress' => false,
    'strictOn' => false,
    'failover' => [],
    'port'     => 3306,
];

To save your time you can execute the SQL query from PHPMyAdmin to create the users table and insert some random data into it.

CREATE DATABASE demo;
 
CREATE TABLE users (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    name varchar(100) NOT NULL COMMENT 'Name',
    email varchar(255) NOT NULL COMMENT 'Email Address',
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='demo database' AUTO_INCREMENT=1;
 
INSERT INTO `users` (`id`, `name`, `email`) VALUES
(1, 'Paul Bettany', 'paul@gmail.com'),
(2, 'Vanya', 'vanya@gmail.com'),
(3, 'Luther', 'luther@gmail.com'),
(4, 'John Doe', 'john@gmail.com'),
(5, 'Paul Bettany', 'paul@gmail.com'),
(6, 'Vanya', 'vanya@gmail.com'),
(7, 'Luther', 'luther@gmail.com'),
(8, 'Wayne Barrett', 'wayne@gmail.com'),
(9, 'Vincent Ramos', 'ramos@gmail.com'),
(10, 'Susan Warren', 'sussan@gmail.com'),
(11, 'Jason Evans', 'jason@gmail.com'),
(12, 'Madison Simpson', 'madison@gmail.com'),
(13, 'Marvin Ortiz', 'paul@gmail.com'),
(14, 'Felecia Phillips', 'felecia@gmail.com'),
(15, 'Tommy Hernandez', 'hernandez@gmail.com');
Step 4: Installing CodeIgniter4-DataTables Library To install datatable pluing by executing the following comamnd on terminal:
composer require hermawan/codeigniter4-datatables
then open app/Config/autoload.php. add namespace to $psr4 array. see the code below:
public $psr4 = [
    APP_NAMESPACE => APPPATH, // For custom app namespace
    'Config'      => APPPATH . 'Config',
    'PHPSQLParser'          => APPPATH .'ThirdParty/php-sql-parser/src/PHPSQLParser',
    'Hermawan\DataTables'   => APPPATH .'ThirdParty/CodeIgniter4-DataTables/src'
];
Step 5: Create New Model

Create a UserModel.php file in the app/Models/ diretory, then add the given below code.

app/Models/UserModel.php
<?php 
namespace App\Models;
use CodeIgniter\Model;
 
class UserModel extends Model
{
    protected $table = 'users';
    protected $primaryKey = 'id';
    protected $allowedFields = ['name', 'email'];
}
Step 6: Create Controller

In this step we will create a new controller app/Controllers/DatatableController.php file and add the given below code in it.

app/Controllers/DatatableController.php
<?php 
namespace App\Controllers;
use \CodeIgniter\Controller;
use \Hermawan\DataTables\DataTable;
  
class DatatableController extends Controller
{

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        helper('url');
        return view('userView');
    }
    
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function ajaxDataTables()
    {
        $db = db_connect();
        $builder = $db->table('users')->select('name, email, id');
          
        return DataTable::of($builder)
               ->addNumbering() //it will return data output with numbering on first column
               ->toJson();
    }
}
?>
Step 7: Create Routes

In this step, we require to create a route that will be using to display the users list within the Datatables. To generate the routes add the following code inside the app/Config/Routes.php file.

app/Config/Routes.php
$routes->setDefaultController('UsersController');
$routes->get('list', 'UsersController::index');
$routes->get('ajax-datatable', 'UsersController::ajaxDataTables');
Step 8: Display Datatables in Codeigniter

In this step, we will render the data from database and display in Codeigniter template using DataTables. We have included the Datatables CDN link of jQuery and CSS in the footer.

app/Views/userView.php
<!DOCTYPE html>
<html>
<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>CodeIgniter 4 Server Side DataTable Tutorial - Mywebtuts.com</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css" >
    <link href="https://cdn.datatables.net/1.10.24/css/dataTables.bootstrap4.min.css">
</head> 
<body>
    <div class="container">
        <h1 style="font-size:20pt"></h1>
        <h3>Customers Data</h3>
        <table id="table" class="table table-striped table-bordered" cellspacing="0" width="100%">
            <thead>
                <tr>
                    <th>No</th>
                    <th>Name</th>
                    <th>Email</th>
                </tr>
            </thead>
            <tbody></tbody>
            <tfoot>
                <tr>
                    <th>No</th>
                    <th>Name</th>
                    <th>Email</th>
                </tr>
            </tfoot>
        </table>
    </div>
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.24/js/dataTables.bootstrap4.min.js"></script>
    <script type="text/javascript">
    
    /*------------------------------------------
    --------------------------------------------
    DataTable 
    --------------------------------------------
    --------------------------------------------*/
    $(document).ready(function() {
        $('#table').DataTable({ 
            processing: true,
            serverSide: true,
            order: [],
            ajax: "<?php echo site_url('ajax-datatable')?>",
            columnDefs: [
                { targets: 0, orderable: false},
            ]
        });
    });
    </script>
  
</body>
</html>
Step 9 : Run Codeigniter App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Codeigniter app:

php spark serve

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

http://localhost:8080/

It will help you...

#Codeigniter 4