Skip to content

Laravel 5.5 – Optional Objects

Last updated on February 17, 2018

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 :

// user model
function profile(){
    return $this->hasOne(Profile::class);
}

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.

$address = User::find(1)->profile ? User::find(1)->profile->adresss : ''

lets do same with optional() helper:

$address = optional(User::find(1)->profile)->adresss;
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments