Working with Model in CodeIgniter 4 Tutorial

Share this Article
Reading Time: 6 minutes
4,650 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.

Learn More –

Let’s get started.


CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


.env Setup

When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Either we can do via renaming file as simple as that. Also we can do by terminal command.

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.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.


Create Database Table

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 table. Let’s connect with the application.


Database Connection

Open .env file from project root.

Search for DATABASE. You should see the connection environment variables. Give your updated details of database connection string.

 
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------

database.default.hostname = localhost
database.default.database = codeigniter4_app
database.default.username = root
database.default.password = root
database.default.DBDriver = MySQLi
database.default.DBPrefix =
   

Now, database successfully connected with the 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.

//...

$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.

//...

$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.

//...

$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.

//...

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

//...

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

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

We hope this article helped you to learn about Working with Model in CodeIgniter 4 Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

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.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5