CodeIgniter Laravel PHP Example Javascript jQuery MORE Videos New

Model is a PHP class in codeigniter hold the database part for the application


Model is a PHP class in codeigniter hold the database part for the application. It can contains functions to insert, update, and retrieve your application data. Let’s see the below example for better understanding about model:

class Site_model extends CI_Model {

	public $title;
	public $description;
   
	public function get_last_five_entries()
	{
			$query = $this->db->get('site_data', 10);
			return $query->result();
	}

	public function insert_entry()
	{
  $this->title    = $this->input->post('title');                 $this->content  = $this->input->post('description'); 
			
			$this->db->insert('site_data', $this);
	}

	public function update_entry()
	{
			 $this->title    = $this->input->post('title');                 $this->content  = $this->input->post('description'); 

			$this->db->update('site_data', $this, array('id' => $_POST['id']));
	}

}

Model classes are stored inside the application/models/ directory. They can be nested within sub-directories if you want this type of organization.

The basic syntax for model is:

class Model_name extends CI_Model {

}

Here Model_name is the class name.

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

For example, if this is your class:

class Site_model extends CI_Model {

}

Your file will be this:

application/models/Site_model.php

Loading a Model

You can only call a model from controller. To call a model you will use the following method:

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

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

$this->load->model('site/queries');

Once loaded, you will access your model 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 Site_controller extends CI_Controller {

        public function index()
        {
                $this->load->model('Site_model');

                $data['query'] = $this->blog->get_last_five_entries();

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