CodeIgniter 4 CRUD REST APIs Development

Share this Article
Reading Time: 9 minutes
7,774 Views

CodeIgniter 4 is an open source framework of PHP. There are several libraries available in codeigniter 4 which makes application development very easy.

Inside this article we will see the concept of CodeIgniter 4 CRUD REST APIs development. We will discuss about each method of CRUD operation like Create, Read, Update & Delete Request in APIs.

Article is very interesting to learn and super easy to implement.

Learn more –

  • CodeIgniter 4 RESTful APIs with JWT Authentication, Click here.
  • REST API Development with Validation in CodeIgniter 4, Click here.
  • Basic Auth REST API Development in CodeIgniter 4, Click here.
  • Upload Image by REST API in CodeIgniter 4 Tutorial, Click here.

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.

Now, let’s configure database and application connectivity.


.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

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE codeigniter4_app;

Successfully, we have created a database.


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 `members` (
 `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.


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

Back to terminal and run this spark command to create a model file.

$ php spark make:model Member --suffix

It will create MemberModel.php file at /app/Models folder. Open file and write this complete code into it.

<?php

namespace App\Models;

use CodeIgniter\Model;

class MemberModel extends Model
{
	protected $DBGroup              = 'default';
	protected $table                = 'members';
	protected $primaryKey           = 'id';
	protected $useAutoIncrement     = true;
	protected $insertID             = 0;
	protected $returnType           = 'array';
	protected $useSoftDelete        = false;
	protected $protectFields        = true;
	protected $allowedFields        = [
		"name", 
		"email", 
		"mobile"
	];

	// 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          = [];
}

Create Controller

Again, Back to terminal and run this spark command to create a controller file.

$ php spark make:controller Member --restful

It will creates Member.php file at /app/Controllers folder.

Open Member.php and write this complete code into it.

<?php

namespace App\Controllers;
use App\Models\MemberModel;
use CodeIgniter\RESTful\ResourceController;

class Member extends ResourceController
{
	/**
	 * Return an array of resource objects, themselves in array format
	 *
	 * @return mixed
	 */
	public function index()
	{
		$model = new MemberModel();
      
        $data = $model->findAll();
      
        $response = [
            'status' => 200,
            'error' => null,
            'messages' => "Members Found",
            "data" => $data,
        ];
        return $this->respond($response);
	}

	/**
	 * Return the properties of a resource object
	 *
	 * @return mixed
	 */
	public function show($id = null)
	{
		$model = new MemberModel();
      
        $data = $model->where(['id' => $id])->first();
      
        if ($data) {
            $response = [
                'status' => 200,
                'error' => null,
                'messages' => "Member Found",
                "data" => $data,
            ];
            return $this->respond($response);
        } else {
            return $this->failNotFound('No Member Found with id ' . $id);
        }
	}

	/**
	 * Return a new resource object, with default properties
	 *
	 * @return mixed
	 */
	public function new()
	{
		//
	}

	/**
	 * Create a new resource object, from "posted" parameters
	 *
	 * @return mixed
	 */
	public function create()
	{
		$model = new MemberModel();

        $data = [
            'name' => $this->request->getVar('name'),
            'email' => $this->request->getVar('email'),
            'mobile' => $this->request->getVar('mobile'),
        ];

        $model->insert($data);

        $response = [
            'status' => 200,
            'error' => null,
            'messages' => "Member Saved",
        ];
      
        return $this->respondCreated($response);
	}

	/**
	 * Return the editable properties of a resource object
	 *
	 * @return mixed
	 */
	public function edit($id = null)
	{
		//
	}

	/**
	 * Add or update a model resource, from "posted" properties
	 *
	 * @return mixed
	 */
	public function update($id = null)
	{
		$model = new MemberModel();

        $data = [
            'name' => $this->request->getVar('name'),
            'email' => $this->request->getVar('email'),
            'mobile' => $this->request->getVar('mobile'),
        ];

        $model->update($id, $data);

        $response = [
            'status' => 200,
            'error' => null,
            'messages' => "Data Updated"
        ];
        return $this->respond($response);
	}

	/**
	 * Delete the designated resource object from the model
	 *
	 * @return mixed
	 */
	public function delete($id = null)
	{
		$model = new MemberModel();

        $data = $model->find($id);

        if ($data) {

            $model->delete($id);

            $response = [
                'status' => 200,
                'error' => null,
                'messages' => "Data Deleted",
            ];
            return $this->respondDeleted($response);
        } else {
            return $this->failNotFound('No Data Found with id ' . $id);
        }
	}
}

We have all methods available for CRUD operation.


Add Routes

Open Routes.php from /app/Config folder. Add this route into it.

//...

$routes->resource('member');

//...

Here, we have added a resource route which generates routes for CRUD operation.

We have added a single route but when we run spark command to list all application routes, you should see the complete list of routes.

Open terminal and run this command.

$ php spark routes

After running this command, you will see all routes generated by resource controller.


Application Testing

Start development server:

$ php spark serve

CREATE MEMBER API

URL: http://localhost:8080/member

METHOD: POST

HANDLER: \App\Controllers\Member::create

LIST MEMBER API

URL: http://localhost:8080/member

METHOD: GET

HANDLER: \App\Controllers\Member::index

SHOW SINGLE MEMBER API

URL: http://localhost:8080/member/{member_id}

METHOD: GET

HANDLER: \App\Controllers\Member::show/$1

UPDATE MEMBER API

URL: http://localhost:8080/member/{member_id}

METHOD: POST

Parameters – name, email, mobile, _method = PUT (Method Spoofing)

HANDLER: \App\Controllers\Member::update/$1

DELETE MEMBER API

URL: http://localhost:8080/member/{member_id}

METHOD: DELETE

HANDLER: \App\Controllers\Member::delete/$1

To learn about Method Spoofing in CodeIgniter 4, Click here.

We hope this article helped you to learn about CodeIgniter 4 REST APIs Development 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