Home >PHP Framework >Laravel >Very useful Laravel optional helper functions!

Very useful Laravel optional helper functions!

藏色散人
藏色散人forward
2021-07-13 14:42:522224browse

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 of Profile, and a User has A Profile (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!

The above is the detailed content of Very useful Laravel optional helper functions!. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete