Laravel 5.5 – Optional Objects

Laravel 5.5 includes a new Optional class with a new helper() function, which you can think of as a generic null object implementation.

The point of the optional() class and helper is to prevent situations like where you need to fetch a property from a relationship and if its empty this optional helper gracefully handles it without throwing the error like “PHP error: Trying to get property of non-object….” and it will return null.

Assume a Users with profile and its relationship is set up as below :

Now to access the user profile, you will call User::find(1)->profile->address, in this situation if user doesn’t have profile, you will get Trying to get property of non-object error. To handle this issue we did something like below shown in the before Laravel versions, now we can handle in a very clean way.

lets do same with optional() helper:

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.