For any queries you can reach us at infovistarindia@gmail.com / WhatsApp us: +919158876092

Model in CodeIgniter

Introduction

The Model is responsible for managing the data of the application. It receives user input from the Controller. It can contain functions to insert, update, and retrieve your application data.

Model classes reside in the application/models/ directory. They can be nested within sub-directories.

The basic syntax for the model is:


class Model_name extends CI_Model {

}

Let’s see the following example for a better understanding of the model:


class Blog_model extends CI_Model {

	public function add() {
		$data = [
			‘title’		=> ‘Title’,
			‘description’	=> ‘Description’
		];
		// insert(‘table_name‘, ‘array_of_object’)
		$this->db->insert(‘blog_info’, $data);
	}

	public function get_blog_list() {
		$query = $this->db->get(‘blo_info’);
		return $query->result();
	}

}

The file name must match the class name and the first letter of the Model class must be a capital letter.

Load / Call a Model

A this->load->model() method is used to load a model.

Basic syntax: $this->load->model('model_name');

If your model is located in a sub-directory, include the relative path from your model’s directory. For example, if you have a model located at application/models/user/Profile.php you’ll load it using:

$this->load->model('user/profile');

Once the model is loaded, you can access all the public methods using an object with the same name as your class:

$this->load->model('model_name');
$this->model_name->method();

Here is an example of a controller, that loads a model, then serves a view:

class Blog extends CI_Controller {

	public function index() {
    	$this->load->model(‘blog_model’);

        $data[‘list’] = $this->blog_model->get_blog_list();

        $this->load->view('about_us', $data);
   	}
}