0

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?

ndm
  • 59,784
  • 9
  • 71
  • 110
Chrishow
  • 363
  • 1
  • 5
  • 13
  • 1
    You've confirmed that `$this->User->id` is being set correctly? – Greg Schmidt Aug 27 '19 at 15:32
  • Well this [code](int)$this->Session- >read('Users.UserData.User.id'); [/code]has the value and I'm assigning it, I and as far as I know cake works by setting an existing id it tells savefield to modify instead of creating. How else could I debug it? – Chrishow Aug 27 '19 at 15:52
  • Just to output `$this->User->id` after you set it, to be absolutely sure that it's as you expect. These sorts of errors are very often caused by things like typos in the session path you're reading, for example. – Greg Schmidt Aug 27 '19 at 18:26

1 Answers1

0

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.

Chrishow
  • 363
  • 1
  • 5
  • 13