April 15, 2018 —John Koster
The optional
function returns a new instance of "Illuminate\Support\Optional" with the provided value. This helper class allows you to easily retrieve a default, or null
value on method return values or object properties that might not exist. This is useful in situations where you are displaying data, or are simply returning trivial results that might not exist at runtime.
The signature of the optional
function is:
1function optional(2 $value3);
The following example would throw an ErrorException
with the message "Trying to get property of non-object":
1// Imagine that the `$testObject` was returned from2// a method call or API request.3$testObject = null;4 5// Attempt to access a property that does not exist.6$testValue = $testObject->someProperty;
However, if we wrapped the property access in a call to the optional
function, we would instead receive a null
value:
1$testObject = null;2 3$testValue = optional($testObject)->someProperty;
This behavior of the optional
helper function makes it useful for creating presenter classes or validation logic around Eloquent method return results.
The Optional
class also implements the "Illuminate\Support\Traits\Macroable" trait which means that we can dynamically add functionality to the Optional
instance run-time:
1$testObject = optional(null);2 3// Add a method to the Optional instance.4$testObject->macro('testMacro', function () {5 return 'Hello, Universe';6});7 8$value = $testObject->testMacro();
After the above code has executed, the $value
variable would contain Hello, Universe
.
∎
The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.