0

I'm using CI 2.1.3 and I'm having issues with loading models and referring to the CodeIgniter "super object".

For example:

I'm trying to log in using my Login controller:

class Login extends CI_Controller {

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

    public function validate_credentials() {
        $this->load->library('form_validation');
        // Some form validation here...

        $query = $this->Users_model->validate();

        if($query) {    // if the user's credentials validated...
            // something
        } else {
            // something
        }
    }

And when it gets to my Users_model:

class Users_model extends CI_Model {

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

public function validate()
{
    $this->db->where('active', 1);
    $this->db->where('email', $this->input->post('email'));
    $this->db->where('password', md5($this->input->post('password')));
    $query = $this->db->get('user');

    if($query->num_rows == 1)
    {
        return $query;
    }

}
}

I get an error "Fatal error: Call to a member function where() on a non-object in users_model.php on line XX" referring to the first line of validate() function.

I can get it working by using double colon (::) operator in Login controller like Users_model::validate() but I think I shouldn't need that.

I can also get it working by writing something like:

    $ci = get_instance();
    $ci->db->where...

at the start of the Users_model->validate() function, but I think I shouldn't need to do that either.

The database class is being loaded in autoload.php.

So the problem is that $this in my models refers to the model class itself rather than the "super object" it's supposed to. I have no moves left and I'm guessing it's about something very simple but I just can't see it. Please help me.

tereško
  • 58,060
  • 25
  • 98
  • 150
Aki Auvinen
  • 21
  • 1
  • 1
  • I don't understand why this was marked as a duplicate of another question also marked as a duplicate when both do not specifically answer this. See: http://stackoverflow.com/q/8447565/594235 – Sparky Oct 28 '14 at 14:36

1 Answers1

1

Please try by loading CI library like this

  $this->load->library('database');

in __construct() function before loading model: or load this library from autoload file like:

$autoload['libraries'] = array('database','form_validation', 'session');
sandip
  • 3,279
  • 5
  • 31
  • 54
  • Like I already said: "The database class is being loaded in autoload.php." So I have this line in my config/autoload.php: $autoload['libraries'] = array('database', 'session', 'template'); – Aki Auvinen Mar 09 '13 at 14:54