0

Is there a way to get the following to work?

$modelId = null;
$model = MyModel::updateOrCreate(
    ['id' => $modelId],
    [
        'value' => $data['other_value'],
    ]
);

Using PostgreSQL, I am getting the following error: Not null violation: 7 ERROR: null value in column "id" violates not-null constraint.

This is because in Laravel (updateOrCreate(array $attributes, array $values = [])) creates a new instance with $attributes pre-set (eg. ['id' => $modelId]). Then it merges the $values (eg. ['value' => $data['other_value']) for the update which results with MyModel(['id' => null, 'value' => $data['other_value']) instead of MyModel(['value' => $data['other_value']) which would succeed because of the auto-incrementing id field.

I can expand it to the following to fix it, but it just isn't as concise..

$modelId = null;
$model = MyModel::find($modelId);
if (! $model) {
    $model = new MyModel();
}
$model->fill([
    'value' => $data['other_value'],
]);
$model->save();

Because I will have a lot of these upserts, as a last resort, I have also considered creating a Trait or something to override the updateOrCreate() method. However, I would prefer to keep it as natural to the existing framework as possible.

2 Answers 2

2

If there isn't a way, I'll probably just use the following Trait, but to avoid confusion for co-workers I'll keep it as a separate method rather than overriding updateOrCreate():

// app/Traits/UpdateOrCreateOnNull.php
namespace App\Traits;

Trait UpdateOrCreateOnNull {
    public static function updateOrCreateOnNull($id, $values = [])
    {
        if (is_null($id)) {
            $model = new self();
        } else {
            $model = self::find($id);
        }
        $model->fill($values);
        $model->save();
        return $model;
    }
}

Usage:

// app/Models/MyModel.php
use App\Traits\UpdateOrCreateOnNull;

class MyModel extends Model
{
    use UpdateOrCreateOnNull;
    protected $fillable = ['other_value'];
    public $timestamps = false;
}
$ php artisan tinker
>>> $modelId = null
=> null
>>> $data = ['other_value' => 'foobar']
=> [
     "value" => "foobar",
   ]
>>> $model = App\Models\MyModel::updateOrCreateOnNull($modelId, $data)
=> App\Models\MyModel {#3327
     other_value: "foobar",
     id: 2,
   }
1
  • This is actually a genius solution. Thanks Magnie Commented Mar 29 at 9:32
1

updateOrCreate, is a method that will find a record in your database that matches the data entered in the first array. And if it doesn't find it, this method will insert that data into your database.

That is, if you give the first array to look for an id of type null, it will not find it because, probably, that column is a primary key and does not allow null data.

That's why it is your mistake when using that method. Since it does not find any null value id and try to insert it.

Here is the Laravel documentation if you need more references and this examples in Laravel News

2
  • Yeah, you have a good point. It does mention "If the record can not be found, a new record will be inserted with the merged attributes of both arguments". I must have skipped over that while reading the documentation initially. So the functionality is intended as is. Commented Mar 13, 2021 at 21:30
  • Yes, that's right, so if you need to use it, you should use it with other fields that would not be null like the id of your table or others that can be null. How MyModel::updateOrCreate(['id' => 1, 'foo' => 'bar'],['barX' => 'foox', 'barY' => 'fooY']);
    – gaidyjg
    Commented Mar 13, 2021 at 21:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.