Skip to main content

Codeigniter 4 call model function from controller

This code snippet wil provide a solution to call model function from controller in codeigniter 4. You can create a model function in your model which is inside your app\models directory and after that you can call it in your controller’s method by creating a new object on the model class using a new keyword.

  • User model in Codeigniter 4 with CRUD methods

    --PATH app\Models\UserModel.php
    <?php
    namespace App\Models;
    use CodeIgniter\Model;
    
    class UserModel extends Model
    {
        protected $table = 'tbl_users';
        // .. other member variables
        private $db;
    
        public function __construct()
        {
            parent::__construct();
            $this->db = \Config\Database::connect();
            // OR $this->db = db_connect();
        }
    
        public function insert_data($data = array())
        {
            $this->db->table($this->table)->insert($data);
            return $this->db->insertID();
        }
    
        public function update_data($id, $data = array())
        {
            $this->db->table($this->table)->update($data, array(
                "id" => $id,
            ));
            return $this->db->affectedRows();
        }
    
        public function delete_data($id)
        {
            return $this->db->table($this->table)->delete(array(
                "id" => $id,
            ));
        }
    
        public function get_all_data()
        {
            $query = $this->db->query('select * from ' . $this->table);
            return $query->getResult();
        }
    
    }
    

    Here we create the user model in app\models directory with CRUD methods which is used to create a new user, update user data , delete users and get the user data.

  • Call model method in controller in Codeigniter 4

    --PATH app\Controllers\User.php
    <?php
    
    namespace App\Controllers;
    
    use App\Controllers\BaseController;
    use App\Models\UserModel;
    
    class User extends BaseController
    {
        public function index()
        {
            $userModel = new UserModel();
    
            // Add operation
            $userId = $userModel->insert_data(array(
                "name" => "w3codegenerator.com",
                "email" => "[email protected]",
                "phone_no" => "1234567890",
            ));
        }
    }
    

    We have to create a controller file inside controllers directory and here we can call the model method on object created by using a new keyword on user model class.

    To call the model method on an object created by the new keyword on user model you have to include user model in your controller file by using the use keyword like use App\Models\UserModel;.

  • Back to code snippet queries related codeIgniter