Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

RokSiEu's avatar

Understanding of updateOrCreate

Hi,

I'm using this code, to update or create new entry

$data = array('id_mandator'=> 1, 'title' => 'editedvalue');
Mandator::updateOrCreate(['id_mandator'=> $mandator->id_mandator],$data);

And I get

Unknown column 'id' in 'where clause' 

I don't know why, but where clause looks like this

 where `id` is null

It should check if id_mandator exists then update, else insert $data.

I'm starting to think that I don't understand updateOrCreate correctly.

0 likes
2 replies
RokSiEu's avatar
RokSiEu
OP
Best Answer
Level 1

Never mind. I found a solution just when I submitted this posts. I had to define primary key in model

 protected $primaryKey = id_mandator';
3 likes
djkarimi's avatar

Add new function code :

vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php :

public function updateOrInsert(array $attributes, array $values = [])
{
    $instance = $this->where($attributes);
    if ($instance->count() != 0) {
        $instance->update($values);
    } else {
        $instance = $this->updateOrCreate($attributes, $values);
    }
    return $instance;
}
1 like

Please or to participate in this conversation.