...
CodeIgniter, Tutorials

How to add or load a model in Codeigniter?

25 December 2018

In this Blog, we will learn that how we can load a model in codeigniter and how to use method of model using controller.

Load Model in CodeIgniter

In Codeigniter, models will typically be loaded and called from within your controller methods. we can load a model using following method:

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

If model is located in a sub-directory, include the relative path from your model’s directory. For example, if we have a model located at application/models/blog/Posts.php. then we will load it using:

$this->load->model('blog/Posts');

Access Method of Model using Controller

Once our Model loaded, we will access its methods using an object with the same name as our controller:

class Blog_controller extends CI_Controller {
        public function blog()
        {
                $this->load->model('blog');

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

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

Leave a Comments