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.
<?php
namespace App\Models;
use CodeIgniter\Model;
class StudentModel extends Model
{
protected $DBGroup = 'default';
protected $table = 'students';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $insertID = 0;
protected $returnType = 'array';
protected $useSoftDelete = false;
protected $protectFields = true;
protected $allowedFields = [];
// 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 = [];
}
- $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.
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use App\Models\StudentModel;
class UserController extends BaseController
{
public function index()
{
$studentModel = new StudentModel();
//...
}
}
We have created $studentModel an instance of StudentModel.
Next, we can call all methods like insert(), update(), delete() using $studentModel.
Read more