Search code examples
cakephptimestampcakephp-3.0behavior

CakePHP 3.0 Timestamp behavior


I would like to update a timestamp in a users table when a user logs in. I created a datetime field called 'lastLogin'.

From my users controller's login action I call:

$user = $this->Auth->identify();
if ($user) {
     $this->Auth->setUser($user);
     $this->Users->touch($this->Users->get($user['id']), 'Users.afterLogin');
}

And in my Users table I have:

$this->addBehavior('Timestamp', [
    'events' => [
        'Model.beforeSave' => [
            'created' => 'new',
            'modified' => 'always',
        ],
        'Users.afterLogin' => [
            'lastLogin' => 'always'
        ]
    ]
]);

I have tested that the event is triggered and entity property is being updated. However it is not saved to the database.

Is this intended, i.e. do I have to explicitly save the entity, or am I missing something?

Thanks!

Andrius


Solution

  • The behavior only updates the field

    It isn't really clear from the documentation, but the code only updates the field value. The behavior won't actually update the db, it's effectively assumed there would be a call to save later in the same request.