The optional function accepts any argument and allows you to access properties or call methods on that object. If the given object is null, properties and methods will return null instead of causing an error:
$user = (object)['name' => 'Luke', 'father' => (object)['name' => 'Anakin']];
$fatherName = null;
if (!is_null($user->father)) {
$fatherName = $user->father->name;
}
// Example 1 : The optional helper will check if the user's father object's name is set.
$user = (object)['name' => 'Luke', 'father' => (object)['name' => 'Anakin']];
$fatherName1 = optional(optional($user)->father)->name;
// Example 2 : Even if no father is set to Luke this code will work and return null
$user = (object)['name' => 'Luke'];
$fatherName2 = optional(optional($user)->father)->name;
LLoadout is your loadout for Laravel, helping you kickstart your development process. Besides this refactoring site we also make some cool packages and video tutorials !
Go to LLoadout on github