CodeIgniter 4 CRUD Example Tutorial

Share this Article

CodeIgniter 4 is an open source PHP Framework. Inside this article we will see about implementation of CodeIgniter 4 CRUD Tutorial. Nowadays, every application have a common operation CRUD. CRUD stands for Create, Read, Update & Delete.

We will see, about each operation of CRUD in CodeIgniter 4 in a very clear way. We will interact with application database, model etc.

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started CRUD Example in CodeIgniter 4.


Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system. To set application we have multiple options to proceed. Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Settings Environment Variables

When we install CodeIgniter 4, we have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

// Do it to 

CI_ENVIRONMENT = development

Now application is in development mode.


Create Database & Table in Application

We need to create a database. For database we will use MySQL. We have 2 options available to create database. Either we can use PhpMyAdmin Manual interface Or we can use command to create.

CREATE DATABASE codeigniter4_app;

Next, we need a table. That table will be responsible to store data. Let’s create table with some columns.

CREATE TABLE `tbl_members` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(120) DEFAULT NULL,
 `email` varchar(120) DEFAULT NULL,
 `mobile` varchar(45) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Successfully, we have created a database and a table. Let’s connect with the application.


Database Connectivity to Application

Open .env file from project root. Search for DATABASE. You should see the connection environment variables.

Let’s set the value for those to connect with database.

 
#--------------------------------------------------------------------
# DATABASE
#-------------------------------------------------------------------- 
 database.default.hostname = localhost
 database.default.database = codeigniter4_app
 database.default.username = root
 database.default.password = root
 database.default.DBDriver = MySQLi
   

Now, database successfully connected with application.


Application Routes Configuration

To configure application routes, we need to open up the file Routes.php from /app/Config folder. This is the main routes config file where we will put all CRUD routes of application.

//.. Other routes

$routes->match(["get", "post"], "add-member", "Member::addMember");
$routes->match(["get", "post"], "edit-member/(:num)", "Member::EditMember/$1");
$routes->get("list-members", "Member::listMember");
$routes->get("delete-member/(:num)", "Member::deleteMember/$1");

Let’s create Model.


Set Application Model

Model is the face of application with the database. We need a Member Model which will do some basic model configuration.

Models are created at /app/Models. We are going to create MemberModel.php at given location.

$ php spark make:model Member --suffix
<?php

namespace App\Models;

use CodeIgniter\Model;

class MemberModel extends Model
{
	protected $DBGroup              = 'default';
	protected $table                = 'tbl_members';
	protected $primaryKey           = 'id';
	protected $useAutoIncrement     = true;
	protected $insertID             = 0;
	protected $returnType           = 'array';
	protected $useSoftDelete        = false;
	protected $protectFields        = true;
	protected $allowedFields        = [
      'name', 
      'email', 
      'mobile'
    ];

	// Dates
	protected $useTimestamps        = false;
	protected $dateFormat           = 'datetime';
	protected $createdField         = 'created_at';
	protected $updatedField         = 'updated_at';
	protected $deletedField         = 'deleted_at';

	// Validation
	protected $validationRules      = [];
	protected $validationMessages   = [];
	protected $skipValidation       = false;
	protected $cleanValidationRules = true;

	// Callbacks
	protected $allowCallbacks       = true;
	protected $beforeInsert         = [];
	protected $afterInsert          = [];
	protected $beforeUpdate         = [];
	protected $afterUpdate          = [];
	protected $beforeFind           = [];
	protected $afterFind            = [];
	protected $beforeDelete         = [];
	protected $afterDelete          = [];
}

Application Controller Settings

Controller is the functional file. Firstly let’s load helper to Parent Controller i.e BaseController.php. This file is in /app/Controllers folder.

Search helpers in BaseController and load “url” into helpers.

protected $helpers = [‘url’];

After loading this url helper, we will able to use site_url() and base_url() in Controllers & Views else we should have some error.

We will create application controller at /app/Controllers. Let’s create Member.php inside given folder.

$ php spark make:controller Member

Write the following code into /app/Controllers/Member.php

<?php

namespace App\Controllers;

use App\Models\MemberModel;

class Member extends BaseController
{
    public function addMember()
    {
        if ($this->request->getMethod() == "post") {

            $rules = [
                "name" => "required|min_length[3]|max_length[40]",
                "email" => "required|valid_email",
                "mobile" => "required|min_length[9]|max_length[15]",
            ];

            if (!$this->validate($rules)) {

                return view('add-member', [
                    "validation" => $this->validator,
                ]);
            } else {

                $memberModel = new MemberModel();

                $data = [
                    'name' => $this->request->getVar("name"),
                    'email' => $this->request->getVar("email"),
                    'mobile' => $this->request->getVar("mobile"),
                ];

                $memberModel->save($data);

                $session = session();
                $session->setFlashdata("success", "Member created successfully");
                return redirect()->to(base_url('list-members'));
            }
        }

        return view('add-member');
    }

    public function listMember()
    {
        $memberModel = new MemberModel();

        $members = $memberModel->findAll();

        return view('list-members', [
            "members" => $members,
        ]);
    }

    public function editMember($id = null)
    {
        $memberModel = new MemberModel();

        $member = $memberModel->where("id", $id)->first();

        if ($this->request->getMethod() == "post") {

            $rules = [
                "name" => "required|min_length[3]|max_length[40]",
                "email" => "required|valid_email",
                "mobile" => "required|min_length[9]|max_length[15]",
            ];

            if (!$this->validate($rules)) {

                return view('edit-member', [
                    "validation" => $this->validator,
                    "member" => $member,
                ]);
            } else {

                $data = [
                    'name' => $this->request->getVar("name"),
                    'email' => $this->request->getVar("email"),
                    'mobile' => $this->request->getVar("mobile"),
                ];

                $memberModel->update($id, $data);

                $session = session();
                $session->setFlashdata("success", "Member updated successfully");
                return redirect()->to(base_url('list-members'));
            }
        }

        return view('edit-member', [
            "member" => $member,
        ]);
    }

    public function deleteMember($id = null)
    {
        $memberModel = new MemberModel();
        $member = $memberModel->delete($id);

        $session = session();
        $session->setFlashdata("success", "Member deleted successfully");

        return redirect()->to(base_url('list-members'));
    }
}
  • if ($this->request->getMethod() == “post”) {} Checking request type
  • $rules = []; Variable which contains form validation rules.
  • if (!$this->validate($rules)) {} Validating form inputs with specified form validation rules. It returns false when form not satisfies any rule.
  • “validation” => $this->validator Sending form validation messages to view file.
  • $memberModel = new MemberModel(); Creating model instance.
  • $memberModel->save($data); Saving form data to database table
  • $session = session(); Loading session service to use
  • $session->setFlashdata(“success”, “Member created successfully”); – Storing session temp data into success key.
  • $memberModel->findAll() Reading all data
  • $memberModel->where(“id”, $id)->first(); Reading single row data on the basis of given specific id value.

Views Files Setup in Application

We need to create view files. View files for Add Member, Edit Member, List Member. View files will created inside /app/Views.

Let’s create these files step by step.

Create Parent Template

Create a layout file inside /app/Views. File app.php. This is be parent layout.

Open file /app/Views/app.php and write this code.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>CodeIgniter 4 CRUD Tutorial - OnlineWebTutor</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>

   <?= $this->renderSection("body") ?>

</body>
</html>

We will extend this template file to every view file and dynamically attach page views in it’s body.

List Member view file

View File – /app/Views/list-members.php

<?= $this->extend("app") ?>

<?= $this->section("body") ?>

<div class="container" style="margin-top:20px;">
    <div class="row">
        <div class="panel panel-primary">
            <div class="panel-heading">
                List Member
                <a href="<?= base_url('add-member') ?>" style="margin-top: -7px;" class="btn btn-info pull-right">Add Member</a>
            </div>
            <div class="panel-body">

                <?php
                    if(session()->has("success")){
                        ?>
                            <div class="alert alert-success">
                                <?= session("success") ?>
                            </div>
                        <?php
                    }
                ?>

                <table class="table">
                    <thead>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Mobile</th>
                        <th>Action</th>
                    </thead>
                    <tbody>
                        <?php
                        foreach ($members as $value) {
                        ?>
                            <tr>
                                <td><?php echo $value['id']; ?></td>
                                <td><?php echo $value['name']; ?></td>
                                <td><?php echo $value['email']; ?></td>
                                <td><?php echo $value['mobile']; ?></td>
                                <td>
                                    <a href="<?= base_url('edit-member/' . $value['id']); ?>" class="btn btn-info">Edit</a>
                                    <a href="<?= base_url('delete-member/' . $value['id']); ?>" class="btn btn-danger" onclick="return confirm('Are you sure want to delete?')">Delete</a>
                                </td>
                            </tr>
                        <?php
                        }
                        ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?= $this->endSection() ?>

Add Member view file

Create file of add-member.php

Code of /app/Views/add-member.php

<?= $this->extend("app") ?>

<?= $this->section("body") ?>

<div class="container" style="margin-top:20px;">
    <div class="row">
        <div class="panel panel-primary">
            <div class="panel-heading">
                Add Member
                <a href="<?= base_url('list-members') ?>" style="margin-top: -7px;" class="btn btn-info pull-right">List Member</a>
            </div>
            <div class="panel-body">
                <?php if (isset($validation)) : ?>
                    <div class="col-12">
                        <div class="alert alert-danger" role="alert">
                            <?= $validation->listErrors() ?>
                        </div>
                    </div>
                <?php endif; ?>
                <hr>
                <form class="" action="<?= base_url('add-member') ?>" method="post">
                    <div class="form-group">
                        <label for="name">Name</label>
                        <input type="text" class="form-control" name="name" id="name">
                    </div>
                    <div class="form-group">
                        <label for="email">Email</label>
                        <input type="email" class="form-control" name="email" id="email">
                    </div>
                    <div class="form-group">
                        <label for="mobile">Mobile No</label>
                        <input type="text" class="form-control" name="mobile" id="mobile">
                    </div>
                    <button type="submit" class="btn btn-success">Submit</button>
                </form>
            </div>
        </div>
    </div>
</div>

<?= $this->endSection() ?>

Edit Member view file

Create file of edit-member.php

Edit Member view file. /app/Views/edit-member.php

<?= $this->extend("app") ?>

<?= $this->section("body") ?>

<div class="container" style="margin-top:20px;">
    <div class="row">
        <div class="panel panel-primary">
            <div class="panel-heading">
                Update Member
                <a href="<?= base_url('list-members') ?>" style="margin-top: -7px;" class="btn btn-info pull-right">List Member</a>
            </div>
            <div class="panel-body">
                <?php if (isset($validation)) : ?>
                    <div class="col-12">
                        <div class="alert alert-danger" role="alert">
                            <?= $validation->listErrors() ?>
                        </div>
                    </div>
                <?php endif; ?>
                <hr>
                <form class="" action="<?= base_url('edit-member/' . $member['id']) ?>" method="post">
                    <div class="form-group">
                        <label for="name">Name</label>
                        <input type="text" class="form-control" name="name" id="name" value="<?= $member['name'] ?>">
                    </div>
                    <div class="form-group">
                        <label for="email">Email</label>
                        <input type="email" class="form-control" name="email" id="email" value="<?= $member['email'] ?>">
                    </div>
                    <div class="form-group">
                        <label for="mobile">Mobile No</label>
                        <input type="text" class="form-control" name="mobile" id="mobile" value="<?= $member['mobile'] ?>">
                    </div>
                    <button type="submit" class="btn btn-success">Submit</button>
                </form>
            </div>
        </div>
    </div>
</div>

<?= $this->endSection() ?>

Finally, we have create each configuration of this CodeIgniter 4 CRUD Tutorial. Each step includes database, model, controllers, views settings.


Application Testing

Open project into terminal and start development server.

$ php spark serve

Run application into browser

List Member Page – http://localhost:8080/list-members

Add Member Page – http://localhost:8080/add-member

Edit Member Page – http://localhost:8080/edit-member/1

Delete Member URL – http://localhost:8080/delete-member/1

We hope this article helped you to learn about CodeIgniter 4 CRUD Tutorial in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Find More on CodeIgniter 4 here

Leave a Comment