Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cakephp: afterSave() on insert only?

Tags:

cakephp

I want to detect if a new record was inserted or an old record was updated in afterSave(), but I have no idea how.

I thought about writing a config variable in the beforeSave() (where I can detect an insert, if the id isn't set) but maybe that's not a safe way of doing it.

Any ideas?

like image 635
skerit Avatar asked Dec 26 '22 18:12

skerit


2 Answers

You can do it using afterSave( $model, $created ) function.

Because, the second argument of the afterSave() function is Boolean and will true if a new row is created else it will gives you false.

like image 60
thecodeparadox Avatar answered Jan 05 '23 16:01

thecodeparadox


You can check this by writing the following lines of code here:

public function afterSave(Event $event, Entity $entity, array $options) {
    if ($entity->isNew()) {
        // do whatever you need to do here.
    }
}
like image 39
Amuk Saxena Avatar answered Jan 05 '23 15:01

Amuk Saxena