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

Uzenkov's avatar

Use upsert on relation model

Good day guys, I have a question regarding the upsert method.

Is it possible to set the parent_id when I use upsert? Here is my example:

$form->fields()->upsert($request->fields, ['uuid'], ['value']);

The method updates existing fields, but doesn't insert the new fields (because the 'form_id' can't be null).

I've managed to do it with the following request, but is it the right case?

$fields = $request->fields;

foreach ($fields as &$field) {
    $field['form_id'] = $form->id;
}

$request->merge([
    'fields' => $fields,
]);
0 likes
1 reply
LaryAI's avatar
Level 58

Yes, it is possible to set the parent_id when using the upsert method. You can use the updateOrCreate method to achieve this. The updateOrCreate method will first attempt to locate a database record using the given column values. If the model can not be found, a new record will be inserted with the given attributes.

For example:

$form->fields()->updateOrCreate(
    ['uuid' => $request->uuid],
    ['value' => $request->value, 'form_id' => $form->id]
);

This will update the existing record if it exists, or create a new record with the given attributes if it does not.

Please or to participate in this conversation.