Working with Model in CodeIgniter 4 Tutorial

Share this Article
Reading Time: 6 minutes
787 Views

Inside this article we will see the concept of Model methods of CodeIgniter 4. It is way of interacting with database and perform database operations.

Other ways to query with database is –

To get more idea about working with database, Click here.

Here, we will see Methods of Model in CodeIgniter 4 for all CRUD operations.

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.


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.


Turn Development Mode On

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_students (
    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.


Create Model

Open project into terminal and run this spark command.

$ php spark make:model Student --suffix

It will create a file with name StudentModel.php at /app/Models folder.


Load Model Instance

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();

We have created an $object an instance of StudentModel.

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


Create Controller

Open project into terminal and type this spark command.

$ php spark make:controller Student --suffix

It will create a file with name StudentController.php at /app/Controllers folder.

We will see all model CRUD methods by the help of this StudentController.php controller file.


Model – Insert & Insert Batch Method

To insert data into table we have insert() and insertBatch() method available by this model $object instance.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\StudentModel;

class StudentController extends BaseController
{
	public function insertData()
	{
		$object = new StudentModel();

		$object->insert([
			"name" => "Sanjay Kumar",
			"email" => "test@gmail.com",
			"mobile" => "9879638521"
		]);

		// Insert rows in bulk
		$object->insertBatch([
			[
				"name" => "Sanjay Kumar",
				"email" => "test@gmail.com",
				"mobile" => "9879638521"
			],
			[
				"name" => "Ashish Kumar",
				"email" => "ashish@gmail.com",
				"mobile" => "6541231333"
			]
		]);
	}
}

Create Route

Open Routes.php from /app/Config folder.

//.. Other routes

$routes->get("insert-student", "StudentController::insertData");

URL: http://localhost:8080/insert-student


Model – Update Method

To update data into table we have update() method available by this model $object instance.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\StudentModel;

class StudentController extends BaseController
{
	public function updateData()
	{
		$object = new StudentModel();

		// Updated data
		$object->set([
			"name" => "Sanjay Kumar",
			"email" => "test@gmail.com",
			"mobile" => "9879638521"
		]);
		// where condition
		$object->where([
            "id" => 2
		]);
		// Calling update() method
		$object->update();
      
        // OR
		// $$object->where([$condition])->set([$data])->update()
	}
}

Create Route

Open Routes.php from /app/Config folder.

//.. Other routes

$routes->get("update-student", "StudentController::updateData");

URL: http://localhost:8080/update-student


Model – Delete Method

To delete data from table we have delete() method available by this model $object instance.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\StudentModel;

class StudentController extends BaseController
{
	public function deleteData()
	{
		$object = new StudentModel();
		
		// where condition
		$object->where([
			"id" => 2
		]);
		// Calling delete() method
		$object->delete();

		// OR
		// $object->where([$condition])->delete()
	}
}

Create Route

Open Routes.php from /app/Config folder.

//.. Other routes

$routes->get("delete-student", "StudentController::deleteData");

URL: http://localhost:8080/delete-student


Model – Select Methods

To get data from table we have get() method available by this model $object instance.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\StudentModel;

class StudentController extends BaseController
{
	public function selectData()
	{
		$object = new StudentModel();
		
		// Get all rows
		$all_students = $object->findAll();

		// Get a single row
		$student = $object->find(3);
		print_r($student);
	}
}

Create Route

Open Routes.php from /app/Config folder.

//.. Other routes

$routes->get("get-student", "StudentController::selectData");

URL: http://localhost:8080/get-student

To learn more about CodeIgniter 4 Model & Enity, Click here.

Learn More –

  • Running Raw Queries in CodeIgniter 4 Tutorial, Click here.

We hope this article helped you to learn about Working with Model in CodeIgniter 4 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