Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP: get user info in models

I'm moving some of my find code inside models.

Previously in my controller I had

$this->Book->Review->find('first', array(
    'conditions' => array(
        'Review.book_id' => $id,
        'Review.user_id' => $this->Auth->user('id')
    )
));

so in my Review model I put something like

function own($id) {
    $this->contain();
    $review = $this->find('first', array(
        'conditions' => array(
            'Review.book_id' => $id,
            'Review.user_id' => AuthComponent::user('id')
        )
    ));
    return $review;
}

So I'm calling AuthComponent statically from the Model. I know I can do this for the method AuthComponent::password(), which is useful for validation. But I'm getting errors using the method AuthComponent::user(), in particular

Fatal error: Call to a member function check() on a non-object in /var/www/MathOnline/cake/libs/controller/components/auth.php on line 663

Is there a way to get the info about the currently logged user from a model?

like image 489
Andrea Avatar asked Jan 27 '10 20:01

Andrea


2 Answers

I think this is not good idea to get value from Session. Better solution to get logged user id inside any model simply try this:

AuthComponent::user('id');

This will work almost every where. View, Model and Controller

like image 60
Fury Avatar answered Nov 16 '22 02:11

Fury


The way that I use is this:

App::import('component', 'CakeSession');        
$thisUserID = CakeSession::read('Auth.User.id');

It seems to work quite nicely :-)

like image 36
Ben Hitchcock Avatar answered Nov 16 '22 04:11

Ben Hitchcock