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.