Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 661
bolshas Avatar asked May 14 '26 03:05

bolshas


1 Answers

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.

like image 133
AD7six Avatar answered May 16 '26 11:05

AD7six



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!