'How does Laravel optional() work?
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?
Solution 1:[1]
Also, bear in mind that in PHP 8+ you can use the null safe operator to have the same behavior with cleaner look:
// PHP 8+
$this->events()->create([
'category_a' => $event?->categoryA,
'category_b' => $event?->categoryB,
'user' => $event->user?->accountId,
]);
It is also chainable and can be used with methods:
// before PHP 8
$country = null;
if ($session !== null) {
$user = $session->user;
if ($user !== null) {
$address = $user->getAddress();
if ($address !== null) {
$country = $address->country;
}
}
}
// PHP 8+
$country = $session?->user?->getAddress()?->country;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sasha MaximAL |
