CodeIgniter 4 - Basic CRUD and Form Validation Example (Part 1)

Posted by Ridwan Fadilah on Jun 26, 2020 - 02:51 am

Basic CRUD and Form Validation Example (Part 1)

Learn the Basic CRUD and Form Validation Examples of CodeIgniter 4. Accessing, Creating, Connecting to Database, and Configuring your Model.

CRUD (Create, Read, Update, Delete) is the most needed to make a dynamic website. CRUD are four basic in programming used for data manipulation. You can use it for inserting data, finding data, modify data, and deleting data from the database.

In this tutorial, I'll show you an example of how to make CRUD operation and Validate the data input by using the CodeIgniter 4 Framework.

CodeIgniter's Model

The official CodeIgniter has told the users about their new Model features in this version.

CodeIgniter does provide a model class that provides a few nice features, including:

  • automatic database connection
  • basic CRUD methods
  • in-model validation
  • automatic pagination
  • and more

This class provides a solid base from which to build your own models, allowing you to rapidly build out your application’s model layer.


Creating Your Model

The first is creating your model. You can start to make your CRUD operation from here.

You would find the Models folder in the app folder. Create a new file in the Models folder and named as do you want. After that, fill the blank document with this following syntax:


namespace App\Models;

use CodeIgniter\Model;

class YourModel extends Model

Important to note: The class name is should the same as the file name.

Configure Your Model

Let's configure your model. The model has a few configurations. I'll show you how to config your model but, I just to show you a little config. You can find the full config on the CodeIgniter 4 Official user guide.



namespace App\Models;

use CodeIgniter\Model;

class YourModel extends Model
// your table
protected $table = 'your_table';
// primary key
protected $primaryKey = 'id';
// table fields
protected $allowedFields = ['name', 'email', 'address'];

The $table defines and specifies the primary database table that will work with this model. You can also use more than one table for your queries. This example is only applied for the built-in CRUD methods.

The $primaryKey is the name of the column that used as uniquely identifies in this table.

The $allowedFields specify the fields that allowed to use. This array should be the same as the field names on your database table.

Here's the table structure:

Table Structure Example

Accessing Models on Your Controller

Models are stored in the app/Models directory. To call them in your controller just add this following syntax below the namespace line:

use App\Models\YourModel;
Accessing Your Models

Insert Data (Create)

To make it easier to understand, I'll show you the folder structure for this example:

Folder Structure

To make a 'create' operation of CRUD, we'll work with three files:

  • your form page.php
  • controller
  • model

Prepare your form input page:

<?= form_open('form/create'); ?>

<form action="" method="post">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" value="<?= set_value('name'); ?>">
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" name="email" value="<?= set_value('email'); ?>">
<div class="form-group">
<label for="address">Address</label>
<input type="text" class="form-control" name="address" value="<?= set_value('address'); ?>">

<button type="button" class="btn btn-secondary" onclick="window.location.href='<?= base_url('home'); ?>'">Back</button>
<button type="submit" class="btn btn-primary">Save</button>

The <?= form_open('your-controller/create'); ?> line is the form action, so, keep the action attribute blank.

Be sure the value of the 'for' attribute is the same as the 'name' attribute.

The <?= set_value(); ?> is used to keep the input value when the input is not valid.

Keep the value when the input is not valid

Form Controller:

//load helper
public function __construct()

// load your form index page
public function index()

$data['pageTitle'] = 'Form Index';

return view('form-folder/form-index', $data);

// 'create' function
public function create()
// load validation
$validation = \Config\Services::validation();

// load model
$model = new YourModel();

$data['pageTitle'] = 'Create';

if ($validation->run($_POST, 'new') == false) {
echo '<div>' . $validation->listErrors() . '</div>';
echo view('form-folder/form-index', $data, $_POST);
} else {
return $this->response->redirect(site_url('home'));


public function createNew()

I use the $_POST (super global variable) to make it simpler.

The 'new' at this line $validation->run($_POST, 'new'), is the variable name of the validation rules.

The validation didn't work yet. You should set the form validation rules first to make it work.

The echo '<div>' . $validation->listErrors() . '</div>'; is the error messages. That will display by the browser like this:

Validation Error / Error Messages

Form Validation Rules

To make the 'create' function above work, you should set the form validation rules first. Configure the validation in the Validation.php file. You can find it on the app/config directory.

Here's the example of the validation rules:

// Rules

// Form Validation Rules
public $new = [
'name' => 'required',
'email' => 'required|valid_email|is_unique[]',
'address' => 'required|min_length[20]',

The $new is the variable name of the validation rules, use that to call the validation rules on your controller.

$validation->run($_POST, 'new')

Now, you can insert data into the database. The function/operation now could be used.

Finding Data (Read)

Finding data are simpler than insert data because you no need to use the validation. By using the built-in CRUD operation in CodeIgniter 4, you can run the 'read' function with a short code, except you specify the queries of the specific data.

I want to display the query on my home page.

Display The Query

The page structure:

Page Structure


Home Controller

public function index()
$model = new YourModel();

$data['pageTitle'] = 'Home Index Page';

// load table
$data['table'] = $model->getList();

// load view
return view('index-page', $data);


public function getList()
return $this->orderBy('name', 'ASC')->findAll();

The code above will display by browser like this:

Data Query Result

The orderBy() is used to sort the query result by name.

Okay, that's the basic example of 'create' and 'read' operation use in CodeIgniter 4. Find another example of CRUD operation on the related tutorial below. You can see the video of this tutorial on our YouTube Channel. You can also find the full source code of these examples on our GitHub.

Thanks for reading this tutorial.

Related Articles