When creating new models, I am trying to use the optional()
helper to assign values when they are set. However, when the user
object isn't set in this context, I receive this error: "Undefined property: stdClass::$user"
$this->events()->create([
'category_a' => optional($event)->categoryA,
'category_b' => optional($event)->categoryB,
'user' => optional($event->user)->accountId,
]);
To clarify, the $event
is always set, however it can contain different values. Sometimes category_a
is set, sometimes category_b
is set. The optional helper seems to do the trick here. But, when the object is deeper than one level, it throws an error.
So how do I work with the optional
helper correctly using deeper than one level objects?