CI 4 What are Models?

CodeIgniter 4 Models are those files or functions which interact with application’s database.

Any operations which involves database includes the concept of models. For example – Selecting data, Inserting rows, Updating value, etc.

Models in CodeIgniter 4 are created inside /app/Models.

Every model file extends Model class from CodeIgniter\Model.

Syntax of spark command to create a model

$ php spark make:model <ModelName> <Options>

Example –

$ php spark make:model Student --suffix

It will create a file with name StudentModel.php at /app/Models folder. –suffix flag used to attach Model suffix with the model’s name.

StudentModel.php
  • $DBGroup – Specify database group name. We can create two or more database groups when we work with more than 1 database.
  • $table – Specify associated table name.
  • $primaryKey – Primary key for table
  • $allowedFields – This field contains the number of columns of table for mass assignment.

To use models in CodeIgniter 4 application, first we need to create an instance of that. Here is the way to create.

# Load model

use App\Models\StudentModel;

# Creating model instance

$object = new StudentModel();

Example –

$ php spark make:controller User --suffix

It will create UserController.php file inside /app/Controllers folder.

UserController.php

We have created $studentModel an instance of StudentModel.

Next, we can call all methods like insert(), update(), delete() using $studentModel.

Read more