how do I run updateOrCreate on a relationship if id is null

Viewed 828

I've got this code:

$model->relation->updateOrCreate(['id' => $request->id], $dataArray);

and I recieve the following error:

Call to a member function updateOrCreate() on null

It seems I can't have id be null which can happen in my case, I may send null.

I expected updateOrCreate() to be able to handle this case. If id is null then create new record otherwise just update.

How can I update or create relationship that may not exist without this error getting in the way?

1 Answers

Hey :) just execute the relationship to get the actual eloquent model as below

Note: instead of $model->relation-> do $model->relation()->

$model->relation()->updateOrCreate(['id' => $request->id], $dataArray);
Related