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

Very useful Laravel optional helper functions!

藏色散人
Release: 2021-07-14 08:59:44
forward
2207 people have browsed it

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...
Copy after login

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);
}
Copy after login

Then on our User information page, we want to pass The following code obtains the address of User:

$user->profile->address;
Copy after login

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
Copy after login

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template