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

DavidNineRoc's avatar

The difference between firstOrCreate and updateOrCreate

public function firstOrCreate(array $attributes, array $values = [])
{

    if (! is_null($instance = $this->where($attributes)->first())) {
        return $instance;
    }

    /**
     * @var $instance \Illuminate\Database\Eloquent\Model
     */
    $instance = $this->model->newInstance($attributes + $values)->setConnection('mysql');
    $instance->save();
    
    return $instance;
}


public function updateOrCreate(array $attributes, array $values = [])
{
    if (! is_null($instance = $this->where($attributes)->first())) {
        return $instance;
    }

    $instance = $this->model->newInstance($attributes)->setConnection('mysql');
    $instance->fill($values)->save();

    return $instance;
}

I looked at them. They were actually like this. Do they actually differ if updateOrCreate can override the parameters set above? for instance:

$user = User::firstOrCreate(['uuid' => '12345', 'name' => 'david'], ['name' => 'summer']);

$user = User::updateOrcreate(['uuid' => '12345', 'name' => 'david'], ['name' => 'summer']);

These are the differences I think they are, so what are the actual differences?

0 likes
3 replies
tykus's avatar
tykus
Best Answer
Level 104

firstOrCreate is attempting to find a record (or create that record if one is not found)

updateOrCreate is expecting to update an existing record with the data provided (or create that record if one is not already existing).

In the case of firstOrCreate you would not be updating the existing record (if found using the first argument) with the key/values of the second argument.

8 likes
DavidNineRoc's avatar

I didn't know He Ru informed you.The updateOrCreate I see is the first parameter all conditions .thanks

ssquare's avatar

@tykus Among them which one is faster comparatively? Is it firstOrCreate who will win the race?

Please or to participate in this conversation.