Home >PHP Framework >Laravel >Auxiliary functions in the Laravel framework: introduction to the optional () function
laravel framework There are many auxiliary functions in it. So, what are the very useful auxiliary functions in the new version of Laravel? In the next article, PHP Chinese website will introduce you to a very useful auxiliary method: the optional() function. What is the use of this function? Let's take a closer look.
What are the application scenarios 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 User system, 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 in our For the information page of User
, we hope to obtain the address of User
through the following code:
$user->profile->address;
If we do not have the Profile corresponding to the User in the database, at this time A similar error like the one mentioned at the beginning of the article will occur.
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 If the value is 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() just in case.
The above is the entire content of this article. For more laravel content, please pay attention to the laravel framework introductory tutorial.
Recommended related articles:
Introduction to commonly used auxiliary functions in the Laravel framework
Laravel5.5 new Features: Analysis of the preset command
Related course recommendations:
The latest five Laravel video tutorial recommendations in 2017
The above is the detailed content of Auxiliary functions in the Laravel framework: introduction to the optional () function. For more information, please follow other related articles on the PHP Chinese website!