In the new version of Laravel, there is a very useful auxiliary method: optional()
What is the application scenario of this method? In fact, if you write more code, you will often encounter error messages similar to the following:
Call to a member function on null object...
This is actually because a certain object is empty in our code, so when we call a method or get an attribute The above error message will be reported. For example, let's take an example:
In the system of
User
, we also have the Model file ofProfile
, and aUser
has AProfile
(Profile
contains the user's address information)
public function profile(){ return $this->hasOne(Profile::class); }
Then on our User
information page, we want to pass The following code obtains the address of User
:
$user->profile->address;
If we do not have the Profile
corresponding to the User
in the database, this time it will A similar error occurred as mentioned at the beginning of the article.
So, at this time,
optional()
can come in handy
We only need to get the user’s address information like this:
optional$user->profile)->address
At this time, even if profile
is null (null
), this line of code will not report an error, but will display an empty string.
Isn’t it very useful! With the helper function optional()
, in many similar codes, when you are not sure whether the object will be null
, you can add optional ()
Come for insurance!