Refactoring to the optional helper The optional helper gives you a clean syntax, instead of using checks https://laravel.com/docs/6.x/helpers#method-optional
requires: laravel 6.x

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:

Original code



        $user       = (object)['name' => 'Luke''father' => (object)['name' => 'Anakin']];
        
$fatherName null;
        if (!
is_null($user->father)) {
            
$fatherName $user->father->name;
        }

        

Refactored code



        // 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;

        

Here is the output of the code

This is the output of original

Hi Luke, Anakin here , I'm your father

This is the output of refactor - example 1

Hi Luke, Anakin here , I'm your father

This is the output of refactor - example 2

Hi Luke, here , I'm your father

Want to learn more from LLoadout ?

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