Laravel get model attribute: difference between two methods

I found out that there are two ways to get / display a model attribute with Laravel. I could create a function in User.php, for example:

public function getUsername() {
    return $this->username;
}

Then display the username as follows:

{{{ Auth::user()->getUsername() }}}

Or I could just do it without having to create a function:

{{{ Auth::user()->username }}}

What is the difference between these two methods?

+4
source share
4 answers

. , . , , , 2 , :

public function getUserAge() {
    return $this->username.', '.$this->age;
}

{{{ Auth::user()->getUserAge() }}}

.

accessor mutators , , / .

+3

$someObject->username __get() attributes, username , ( ) attributes, getUserName(), , . , .

__get(), . PHP.

non-existing, , /t first_name last_name /, full_name Laravel . , , , :

public function getFullNameAttribute()
{
    return $this->first_name . ' ' . $this->last_name;
}

, {{ $user->full_name }} .

+4

, - , , ( ).

( $this->username) Illuminate\Database\Eloquent\Model:

/**
 * Dynamically retrieve attributes on the model.
 *
 * @param  string  $key
 * @return mixed
 */
public function __get($key)
{
    return $this->getAttribute($key);
}

Completing this function call with your own is optional.

+2
source

No distinctive feature is a class property or field , and another is the getter method, which also returns this field. This is just a general example of OOP.

Since this is a model object, you can call all of these methods and properties of the model if they are public and protected.

+1
source

All Articles