Simple CRUD App in CodeIgniter 4

CRUD Introduction

Installation & Environment Setup

composer create-project codeigniter4/appstarter ci4
git clone <https://github.com/codeigniter4/framework.git>
database.default.hostname = localhost
database.default.database = ci4
database.default.username = root
database.default.password =
database.default.DBDriver = MySQLi
database.default.DBPrefix =

Implementing the CRUD Operations

Creating Model & Migration

  1. The Model handles the data passed between the database and the user interface.
  2. The View is information that is being presented to a user.
  3. The Controller serves as an intermediary among the Model, the View, and any other resources needed to process the HTTP request and generate a web page.
php spark make:model User
php spark make:migration users
<?phpnamespace App\\Models;use CodeIgniter\\Model;class User extends Model
{
protected $DBGroup = 'default';
protected $table = 'users';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $insertID = 0;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $protectFields = true;
protected $allowedFields = ['name', 'age'];
// 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 = [];
}
<?phpnamespace App\\Database\\Migrations;use CodeIgniter\\Database\\Migration;class Users extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 5,
'auto_increment' => true,
],
'name' => [
'type' => 'VARCHAR',
'constraint' => '100',
],
'age' => [
'type' => 'VARCHAR',
'constraint' => '3',
],
]);
$this->forge->addKey('id', true);
$this->forge->createTable('users');
}
public function down()
{
$this->forge->dropTable('users');
}
}
php spark migrate

Creating the Controller and Routes

php spark make:controller Users --restful
<?phpnamespace App\\Controllers;use CodeIgniter\\RESTful\\ResourceController;class Users extends ResourceController
{
/**
* Return an array of resource objects, themselves in array format
*
* @return mixed
*/
public function index()
{
//
}
/**
* Return the properties of a resource object
*
* @return mixed
*/
public function show($id = null)
{
//
}
/**
* Return a new resource object, w/9,.ith default properties
*
* @return mixed
*/
public function new()
{
//
}
/**
* Create a new resource object, from "posted" parameters
*
* @return mixed
*/
public function create()
{
//
}
/**
* Return the editable properties of a resource object
*
* @return mixed
*/
public function edit($id = null)
{
//
}
/**
* Add or update a model resource, from "posted" properties
*
* @return mixed
*/
public function update($id = null)
{
//
}
/**
* Delete the designated resource object from the model
*
* @return mixed
*/
public function delete($id = null)
{
//
}
}
$routes->get('/', function() {    return redirect()->to('users');
});
$routes->resource('users'); // RESTful resource
  • GET /users is mapped to index()
  • GET /users/new is mapped to new()
  • POST /users is mapped to create()
  • GET /users/(:segment) is mapped to show()
  • GET /users/(:segment)/edit is mapped to edit()
  • PUT/PATCH /users/(:segment) is mapped to update()
  • DELETE /users/(:segment) is mapped to delete()

C: Implementing the Create Operation and Adding a Form

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CodeIgniter 4 Crud App</title>
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body class="my-5">
<div class="container">

<?php
if(session()->getFlashdata('status') != '') { echo '<div class="alert alert-info">'.session()->getFlashdata('status').'</div>';
}
?>
<?= $this->renderSection('content') ?>
</div> https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous">
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous">
</body>
</html>
<h3>CodeIgniter 4 - Simple CRUD App</h3><div class="text-end my-2">
<a href="/users/new" class="btn btn-success">
Create New
</a>
</div>
<?= $this->extend('home') ?>
<?= $this->section('content') ?>
<form action="/users" method="post"> <h3>Create New User</h3><br> <div class="mb-3 row col-6">
<?php csrf_field() ?>
<label class="form-label">Name</label>
<input type="text" class="form-control" name="name" required>
</div>
<div class="mb-3 row col-6">
<label class="form-label">Age</label>
<input type="number" class="form-control"name="age" required>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form><?= $this->endSection() ?>
private $db;

public function __construct()
{
$this->db = db_connect();
}
public function new()
{
return view('new_user');
}
public function create()
{
$data = [
'name' => $this->request->getPost('name'),
'age' => $this->request->getPost('age')
];

$result = $this->db->table('users')->insert($data);

$status = ($result) ? 'Record has been inserted :)': 'Record has not been inserted :(';

return redirect()->to(base_url('users'))->with('status', $status);
}
Create new user form

R: Implementing the Read Operation

public function index()
{
$users = $this->db->table('users')->get()->getResult();

$data['users'] = $users;

return view('read_users',$data);
}
<?= $this->extend('home') ?>
<?= $this->section('content') ?>
<?= $this->include('Templates/header') ?>
<table class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Age</th>
<th scope="col">Edit</th>
<th scope="col">Delete</th>
</tr>
</thead>
<tbody>
<?php foreach($users as $user) : ?> <tr>
<td><?= $user->id ?></td>
<td><?= $user->name ?></td>
<td><?= $user->age ?></td>
<td>
<a href="<?= base_url('/users/'.$user->id.'/edit') ?>" class="btn btn-primary">Edit</a>
</td>
<td>
<a class="btn btn-danger" onclick='if(confirm(`Do you want delete this record`)) { document.forms[`form_<?= $user->id ?>`].submit() }'>Delete</a>
</td>
</tr>
<!-- DELETE Form -->
<form action='/users/<?= $user->id ?>' method='post' name='form_<?= $user->id ?>' class="d-none">
<?= csrf_field() ?>
<input type='hidden' name='_method' value='DELETE' />
</form>

<?php endforeach ?>
</tbody>
</table>
<?= $this->endSection() ?>

U: Implementing the Update Operation

<?= $this->extend('home') ?>
<?= $this->section('content') ?>
<form action="/users/<?= $user->id; ?>" method="post"> <h3>Update User Data for Id No: <?= $user->id; ?></h3><br> <div class="mb-3 row col-6">
<?php csrf_field() ?>
<input type="hidden" name="_method" value="PUT" />
<input type="hidden" name="id" value="<?php echo $user->id; ?>">
<label class="form-label" required>Name</label>
<input type="text" class="form-control" name="name" value="<?= $user->name ?>" required>
</div>
<div class="mb-3 row col-6">
<label class="form-label">Age</label>
<input type="number" class="form-control"name="age" value="<?= $user->age ?>">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form><?= $this->endSection() ?>
use App\Models\User;public function edit($id = null)
{
$user = $this->db->table('users')->getWhere(['id'=>$id],1)->getRow();
$data['user'] = $user;

return view('update_form',$data);

}
public function update($id = null)
{
$user = new User();

$data = [
'name' => $this->request->getPost('name'),
'age' => $this->request->getPost('age'),
];
$result = $user->update($id, $data);
$status = ($result) ? 'Records has been updated :)': 'Records has not been updated :(';

return redirect()->to(base_url('users'))->with('status', $status);
}
  • edit(): As shown in the above code, edit() in the app\\Controllers\\Users.php fetches the respected user from the $id parameter and passes it to the update_form view.
  • update(): It is responsible for updating the given data from the update_form into the users table. Here, we are importing the User Model into the controller and assigning it to the $user variable. With the help of $id parameter, we are able to update the concerned user with $data variable. Right after executing the query, we are redirecting the user to /users with result status.

D: Implementing the Delete Operation

public function delete($id = null)
{
$result = $this->db->table('users')->where('id', $id)->delete();

$status = ($this->db->affectedRows()) ? 'Records has been deleted :)': 'Records has not been deleted :(';

return redirect()->to(base_url('users'))->with('status', $status);
}
<!-- DELETE Form -->
<form action='/users/<?= $user->id ?>' method='post' name='form_<?= $user->id ?>' class="d-none">
<?= csrf_field() ?>
<input type='hidden' name='_method' value='DELETE' />
</form>

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store