Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP - How to check in beforeSave if it's an INSERT or UPDATE

In my model's beforeSave method, how can I check if the save operation is going to be an INSERT or an UPDATE?

I want to add to the model data, but only if it's inserting a new row.

like image 811
BadHorsie Avatar asked Dec 04 '12 12:12

BadHorsie


2 Answers

You can just check in the data if the id exists:

function beforeSave($options = array())
{
  if(empty($this->data[$this->alias]['id']))
  {
    //INSERT
  }
  else
  {
    //UPDATE
  }
}
like image 104
nIcO Avatar answered Oct 19 '22 16:10

nIcO


This is how you would do in Cakephp 4 (in case someone is looking for it)

EDIT it also applies to Cakephp 3 as BadHorsie stated

public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options)
{
    if ($entity->isNew()) {
       //INSERT
    }else{
       //UPDATE
    }
}
like image 21
Olovskos Avatar answered Oct 19 '22 18:10

Olovskos