How to determine in afterSave hook if record was created or updated?


#1

Hi,

In the afterSave hook of a model, I am trying to determine whether the record was created or updated.
My approach was: if ID is dirty, it was created:

   if($this->isDirty(['id'])) {
        $tour_audit->set('type', 'CREATE');
    }
    //case change
    else {
        $tour_audit->set('type', 'CHANGE');
    }

But this does not work, id is not in Model->dirty.
Any hint how I could get that info?

Best regards
Philipp


#2

i usually use - if ($this->loaded()), but perhaps there is a better way.


#3

omg this is sooooo embarrasing - I am using Model->loaded() in at least 20 places in my code so far :slight_smile:


#4

Hi,

unfortunately it does not seem so easy. Model->loaded() only checks if id !== null, which is always true in afterSave: in Model->save(), the id is set on insert before afterSave hook is called:

    // Collect all data of a new record
    $this->id = $to_persistence->insert($this, $data);

so in afterSave Hook id is always set.
At the moment I can’t think of a proper way to determine in afterSave if record was inserted or updated… can you?

Thx again
Philipp


#5

The only way I found was to move the logic to a function and call it from afterInsert and afterUpdate hooks:

	$this->addHook('afterInsert', function($m, $id) {
		$m->createAudit('CREATE', $id);
	});
	
	$this->addHook('afterUpdate', function($m) {
		$m->createAudit('CHANGE');
	});

Best regards
Philipp


#6

yes, i think some cleanup is in order there.