CodeIgniter 4 CRUD with API Builders to Build Dynamic Web App

Table Of Content

Introduction

CodeIgniter is a PHP framework that is used to develop web applications. Versions 2 and 3 of CodeIgniter are significantly different from version 4. Only PHP versions 7.2 and later are supported by CodeIgniter 4. If your server does not support the minimum required version of PHP, you should upgrade your PHP version prior to installation and configuration.

CodeIgniter 4 cannot run in a case where your server does not have any of these extensions enabled, i.e intl extension, php-json, php-mbstring, php-mysqlnd, and php-xml so please check your php.ini file and enable these all if it is not.

In this post, we shall examine the basic installation, configuration, and implementation of CRUD operations as well as the route configuration.

Installation

Please make sure the composer is installed. No worries if it is not installed, you can download the composer from the official website https://getcomposer.org/download/ 

You can check commands based on your OS.

To create a CodeIgniter 4 setup, run this given command into your shell or terminal.

$ composer create-project codeigniter4/appstarter Codeigniter-4

Assuming you have successfully installed an application on your local system.

Environment Configuration

Now, let’s configure the database and application connectivity.

Here, we need to work with the env file for the global variables.

When we install CodeIgniter 4, we will have an env file at the root. To use the environment variables, we need to do env to .env so we can simply rename the file. There is also a command to copy the env file and it will create a new file with it. env, rename the file. Make sure you are in your project directory.

$ cp env .env

Now you are good to go and can use the .env file for the global variables.

There are two environment modes in CodeIgniter, so when we are installing CodeIgniter 4, it starts up in production mode by default. We need to make it in development mode so it will show all the errors on-screen if there are any on the page. 

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 

CI_ENVIRONMENT = development

Now the application is in development mode as it is installed on your local server.

-> Note: Please remove the # of your env variable that you are going to use, otherwise, env is considered as a commented variable.

Database and Table Creation

As usual, we can create a database using the PhpMyAdmin tool OR alternatively by executing commands for the same.

CREATE DATABASE mydb_ci4_app;

The database was successfully created. Now let’s create some required tables for our application to store data.

CREATE TABLE `employee` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `emp_code` varchar(50) DEFAULT NULL,
 `emp_fname` varchar(100) DEFAULT NULL,
 `emp_lname` varchar(100) DEFAULT NULL,
 `emp_email` varchar(255) DEFAULT NULL,
 `emp_phone` varchar(100) DEFAULT NULL,
 `password` varchar(100) DEFAULT NULL,
 `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

The table was created successfully. Now it is time to connect the database to our application.

Connecting Database

As mentioned above, .env the file is responsible for global variables, so database connection variables need to be set up in the .env file that is located in your project root directory.

Open the .env file and search for the “database” keyword. You can see the database configuration variables, so update these variables with your details.

#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------
 
database.default.hostname = localhost
database.default.database = mydb_ci4_app
database.default.username = Username  (Ex. root)
database.default.password = Password  (Ex. root)
database.default.DBDriver = MySQLi
database.default.DBPrefix = Prefix     (Ex. ci_ or tbl_)

Your database is connected successfully with your web application.

Start Web Server

We just need to execute one command to start the application server.

php spark serve

It will create your localhost application URL like http://localhost:8080 

CodeIgniter Route

Typically, there is a one-to-one relationship between a URL string and its corresponding controller class/method. The segments in a URI normally follow this pattern:

website.com/class/function/params[N]

CodeIgniter Routing matches the URL to the predefined routes. If no route match is found, then CodeIgniter throws a page not found exception. Controllers – routes are linked to controllers. Controllers glue the models and views together.

If outing rules are defined in your /app/Config/Routes.php file, they should be similar to the examples below.

$routes->match([‘get’, ‘post’], ‘registration’, ‘Employee::registration’, [‘filter’ => 'noauth']);
$routes->match([‘get’, ‘post’], ‘signin’, ‘Employee::signin’, [‘filter’ => 'noauth']);
$routes->get('account', 'Employee::myaccount', ['filter' => 'auth']);

You can see some important terms, match, get, post, and filter, so all those are checkers of your URL request and if matches are found then only it will allow you to proceed.
Filters check if the particular route needs authentication or not, so if a particular page user must log in, we just need to add a filter as auth and vice versa. We will check later in the next session on how to create and configure the filters in our application, so as of now you can follow the steps without the filter option.

How to Create an Application Model

Models are PHP classes that are designed to work with information in your database.

Models are created and found in the /app/Models directory of your application, so let’s create an employee model.

To create a model, we just need to execute a simple command and it will create the model in the particular directory.

$ php spark make:model Employee --suffix

-> Note: In case you have created a model using the command, please check the model variables as per your table.

<?php
namespace App\Models;
use CodeIgniter\Model;
class EmployeeModel extends Model
{
    protected $DBGroup              = 'default';
    protected $table                = 'employee';
    protected $primaryKey           = 'id';
    protected $useAutoIncrement     = true;
    protected $insertID             = 0;
    protected $returnType           = 'array';
    protected $useSoftDelete        = false;
    protected $protectFields        = true;
    protected $allowedFields        = [
        "emp_code",
        "emp_fname",
        "emp_lname",
        "emp_email",
        "emp_phone",
        "password"
    ];
    /* Date Format definition */
    protected $useTimestamps        = false;
    protected $dateFormat           = 'datetime';
    protected $createdField         = 'created_at';
    /* Validation Rules */
    protected $validationRules      = [];
    protected $validationMessages   = [];
    protected $skipValidation       = false;
    protected $cleanValidationRules = true;
    /* Callbacks definition */
    protected $allowCallbacks       = true;
    protected $beforeInsert         = ["beforeInsert"];
    protected function beforeInsert(array $params)
    {
        $params = $this->passwordHash($params);
        return $params;
    }
        protected function passwordHash(array $params)
    {
            if (isset($params['data']['password'])) {
            $params['data']['password'] = password_hash($params['data']['password'], PASSWORD_DEFAULT);
        }
        return $params;
    }
}

How to Create an Application Controller and CRUD Methods

Controllers are created and found in the /app/Controllers directory of your application, so let’s create an employee controller.

<?php 
namespace App\Controllers;
use App\Models\EmployeeModel;
use CodeIgniter\Controller;

class Employee extends Controller
{
    /**
     * Default method of controller, we are using for listing all records
     */
    public function index(){
        $empModel = new EmployeeModel();
        $returnData['employee'] = $empModel->orderBy('id', 'DESC')->findAll();
        return view('employee/listing', $returnData);
    }

    /**
     * To call the form/view of add new record
     */
    public function add(){
        return view('employee/add');
    }
 

    /**
     * This function is used to store form data into the database
     */
    public function save() {
        $empModel = new EmployeeModel();
        $insertData = [
            'emp_code' => $this->request->getVar('emp_code'),
	        'emp_fname' => $this->request->getVar('emp_fname'),
	        'emp_lname' => $this->request->getVar('emp_lname'),
            'emp_email' => $this->request->getVar('emp_email'),
            'emp_phone'  => $this->request->getVar('emp_phone'),
            'emp_phone'  => $this->request->getVar('emp_phone'),
        ];
        $empModel->insert($insertData);
        return $this->response->redirect(site_url('/employee'));
    }


    /**
     * This function is used to delete a record form from the database
     */
    public function delete($id = null){
        $empModel = new EmployeeModel();
        $empModel->where('id', $id)->delete($id);
        return $this->response->redirect(site_url('/employee'));
    }   

    /**
     * This function is used to load the edit view of a particular record
     */
    public function edit($id = null){
        $empModel = new EmployeeModel();
        $data['employee'] = $empModel->where('id', $id)->first();
        return view('employee/edit', $data);
    }

    /**
     * This function is used to update the data of a particular record
     */
    public function update(){
        $empModel = new EmployeeModel();
        $id = $this->request->getVar('id');
        $updateData = [
           'emp_code' => $this->request->getVar('emp_code'),
	       'emp_fname' => $this->request->getVar('emp_fname'),
           'emp_lname' => $this->request->getVar('emp_lname'),
           'emp_email' => $this->request->getVar('emp_email'),
           'emp_phone'  => $this->request->getVar('emp_phone'),
           'emp_phone'  => $this->request->getVar('emp_phone'),
        ];
        $empModel->update($id, $updateData);
        return $this->response->redirect(site_url('/employee'));
    }
 
}

To define the route of the implemented controller for the CRUD operation,

As mentioned above, we need to define all routes in the /app/Config/Route.php so these are the required routes needed to manage the CRUD operation.

/* CRUD Route definitions */
$routes->get('employee', 'Employee::index');
$routes->get('employee/add', 'Employee::add’);
$routes->post('employee/save', 'Employee::save');
$routes->get('employee/edit/(:num)', 'Employee::edit/$1');
$routes->post('employee/update', 'Employee::update');
$routes->get('employee/delete/(:num)', 'Employee::delete/$1');

Now, let’s check with the employee listing view with the basic layout and table heading and rows.

Show a Listing of Records and Edit and Delete action

We need to create a view file for listing, editing, and adding pages along with the related form fields.

View files reside in the app/Views so here we are going to create our employee directory inside the Views and will create employee section-related view files only inside the employee, so our directory is app/Views/employee for the listing page we are going to create listing.php now.

<!doctype html>
<html>
  <head>
  <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Codeigniter 4 CRUD Tutorial</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-4">
    <div class="d-flex justify-content-end">
        <a href="<?php echo site_url('/employee/add') ?>" class="btn btn-success mb-2">Add Employee</a>
	</div>
    <?php
     if(isset($_SESSION['msg'])){
        echo $_SESSION['msg'];
      }
     ?>
  <div class="mt-3">
     <table class="table table-bordered">
       <thead>
          <tr>
             <th>Employee Code</th>
             <th>First Name</th>
             <th>Last Name</th>
	     <th>Email</th>
	     <th>Phone</th>
             <th>Action</th>
          </tr>
       </thead>
       <tbody>
          <?php if(count($employee)){ ?>
          <?php foreach($employee as $single_emp){ ?>
          <tr>
             <td><?php echo $single_emp['emp_code']; ?></td>
             <td><?php echo $single_emp['emp_fname']; ?></td>
	     <td><?php echo $single_emp['emp_lname']; ?></td>
             <td><?php echo $single_emp['emp_email']; ?></td>
	     <td><?php echo $single_emp['emp_phone']; ?></td>
             <td>
              <a href="<?php echo base_url('employee/edit/'.$single_emp['id']);?>" class="btn btn-primary btn-sm">Edit</a>
              <a href="<?php echo base_url('employee/delete/'.$single_emp['id']);?>" class="btn btn-danger btn-sm">Delete</a>
              </td>
          </tr>
         <?php } ?>
         <?php } ?>
       </tbody>
     </table>
  </div>
</div>

</body>
</html>

This page layout is using bootstrap CSS and without client-side validations. We will check the client and server-side validations in the next article along with the data table one-time listing as well as the server-side requests.

Create an Add Employee Page

We need to use the same directory path as we created our listing page, so let’s create an add.php file for the create new employee record form.

<!DOCTYPE html>
<html>
<head>
  <title>Codeigniter 4 : Add New Employee</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>
  <div class="container mt-5">
    <form method="post" id="employee_add" name="employee_add" 
    action="<?= site_url('/employee/save') ?>">
      <div class="form-group">
        <label>Employee Code</label>
        <input type="text" name="emp_code" class="form-control">
      </div>
      <div class="form-group">
        <label>First Name</label>
        <input type="text" name="emp_fname" class="form-control">
      </div>
      <div class="form-group">
        <label>Last Name</label>
        <input type="text" name="emp_lname" class="form-control">
      </div>
      <div class="form-group">
        <label>Email</label>
        <input type="email" name="emp_email" class="form-control">
      </div>
      <div class="form-group">
        <label>Phone</label>
        <input type="text" name="emp_phone" class="form-control">
      </div>
      <div class="form-group">
        <label>Password</label>
        <input type="password" name="password" class="form-control">
      </div>
      <div class="form-group">
        <button type="submit" class="btn btn-primary btn-block">Store</button>
      </div>
    </form>
  </div>
  
</body>
</html>

Let’s go for the edit action of the particular record, so we need to create a new file inside the same directory i.e app/Views/employee and our file name is edit.php.

Edit Form of the Particular Record

<!DOCTYPE html>
<html>
<head>
  <title>Codeigniter 4 : Update Employee</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>
  <div class="container mt-5">
    <form method="post" id="employee_update" name="employee_update" 
    action="<?= site_url('/employee/update') ?>">
    <div class="form-group">
        <label>Employee Code</label>
        <input type="text" name="emp_code" value="<?php echo $employee['emp_code']; ?>" class="form-control">
    </div>
    <div class="form-group">
        <label>First Name</label>
        <input type="text" name="emp_fname" value="<?php echo $employee['emp_fname']; ?>" class="form-control">
    </div>
    <div class="form-group">
        <label>Last Name</label>
        <input type="text" name="emp_lname" value="<?php echo $employee['emp_lname']; ?>" class="form-control">
    </div>
    <div class="form-group">
        <label>Email</label>
        <input type="email" name="emp_email" value="<?php echo $employee['emp_email']; ?>" class="form-control">
    </div>
    <div class="form-group">
        <label>Phone</label>
        <input type="text" name="emp_phone" value="<?php echo $employee['emp_phone']; ?>" class="form-control">
    </div>
    <div class="form-group">
        <label>Password</label>
        <input type="password" name="password" value="<?php echo $employee['emp_phone']; ?>" class="form-control">
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-primary btn-block">Update</button>
    </div>
</form>
</div>
</body>
</html>

And as we have defined the delete action, it will call the matched route and will delete the particular record.

That’s all with the CodeIgniter 4 CRUD operation

In the end, we were successful in completing the CodeIgniter 4 CRUD operation lesson. In this tutorial, we have started from the very beginning by putting everything in its appropriate place and going through all of the fundamentals.

If there is still a chance that you may be uncertain about the whole process, so hire a CodeIgniter developer to assist you. 

author
Jigar Shah is the Founder of WPWeb Infotech - a leading Web Development Company in India, USA. Being the founder of the company, he takes care of business development activities and handles the execution of the projects. He is Enthusiastic about producing quality content on challenging technical subjects.

Leave a comment