How can you add or load a model in CodeIgniter?

To load models in controller functions, use the following function:

$this->load->model(‘ModelName’);
If in case your model file is located in sub-directory of the model folder, then you have to mention the full path. For example, if your file location is application/controller/models/project/ModelName. Then, your file will be loaded as shown below,

$this->load->model(‘project/ModelName’);

In CodeIgniter, you can add or load a model by following these steps:

  1. Create the Model: First, create a model file under the application/models directory. The filename should match the name of the model class. For example, if your model class is User_model, the filename should be User_model.php.
  2. Define the Model Class: In the model file, define your model class. This class should extend the CI_Model class, which is provided by CodeIgniter. Within this class, you can define your methods to interact with the database or perform any other necessary operations.
    php
    <?php
    class User_model extends CI_Model {
    public function __construct() {
    parent::__construct();
    // Your constructor code here
    }

    // Your model methods here
    }

  3. Load the Model: To load the model into your controller, you can use the load method provided by the CodeIgniter instance. This method is typically available within your controllers.
    php
    $this->load->model('User_model');

    You can then use $this->User_model to access the methods defined in your model within your controller.

Here’s an example of how you might use a loaded model within a controller method:

php
<?php
class MyController extends CI_Controller {
public function __construct() {
parent::__construct();
// Load the model
$this->load->model('User_model');
}

public function index() {
// Use the loaded model
$users = $this->User_model->get_users();
// Process $users...
}
}

In this example, get_users() is a method defined within the User_model class that retrieves user data from the database.