Cakephp date db field upon each and every request

43 Views Asked by At

I'm using cakephp 2.9 and trying to record to database each user last interaction with my web app which is the 'lastactivity' datetime field on the users table.

For this I figured to write the code inside AppController's beforeRender. So my code is this:

Function beforeRender()
{
$this->loadModel('User');
$this->User->id=(int)$this->Session- 
>read('Users.UserData.User.id');
$this->User->savefield('lastactivity', date('Y-m-d H:i:s'));
}

The function runs for every request as expected, but instead of updating the logged user lastactivity value, the savefield is creating new rows in the user table.

Everything seems fine to me, I've dumped the value of the user id and it's ok, I've reread this code like hundred times. My only guess is I'm missing something about the basic functionality if beforeRender...I don't know.

Could anyone help me?

1

There are 1 best solutions below

0
Chrishow On

Thanks Greg, but somehow I solved it; sure not int prettiest way but works like a charm. Just changed the above code for:

function afterFilter()
{
    $id=(int)$this->Session->read('Users.UserData.User.id');
    $this->loadModel('User');
    $this->User->query('UPDATE users SET lastlogin="'.date("Y-m-d H:i:s").'" WHERE id='.$id);
}

I also want to point that changed beforeRender to afterFilter since this way the code runs after the request has loaded, that way I avoid unncecesary delay for the user.