How to load model class in CodeIgniter?

There are three ways to load model classes in a CodeIgniter project. Below mentioned student model class will be used in all the examples


<?php
class Student_model extends CI_Model {

    public function __construct() {
        parent::__construct();
    }

    public function get_users() {
        return $this->db->get('users')->result();
    }
}
First, at the project level, you can include the model in the project's configuration file (autoload.php), making it available throughout the entire application.

Project level model load example Below line we need to add in autoload.php file, after that student model class will be available in entire project.

$autoload['model'] = array('Student_model');
We can call student model class in student controller similarly mentioned below

class Student_controller extends CI_Controller {

    public function index() {
        $users = $this->Student_model->get_students();
    }
}
Second, if the model is needed only within a specific controller, it can be loaded in the controller’s constructor.

Class level model load example As mentioned below, we need to load model class in constructor, after that student model class will be available in all class functions

class Student_controller extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('Student_model');
    }

    public function index() {
        $users = $this->Student_model->get_students();
    }
}
Third, if the model is required only in a particular function, it can be loaded directly inside that function.

Function level model load example As we can see in below example, student model class is loaded in index function only. It will not be available in any other function

class Student_controller extends CI_Controller {

    public function __construct() {
        parent::__construct();
    }

    public function index() {
        $this->load->model('Student_model');
         $users = $this->Student_model->get_students();
    }
}