I found out that there are two ways to get/display a model's attribute with Laravel. I could create a function in User.php
for example:
public function getUsername() {
return $this->username;
}
Then display the username like this:
{{{ Auth::user()->getUsername() }}}
Or I could just simply do this without needing to create a function:
{{{ Auth::user()->username }}}
What is the difference between these two methods?
When Using $someObject->username
in this case the __get()
magic method returns the property from the attributes
array because the username
property is not a public property of the object but it's stored (after populating) inside the attributes
array and when you are calling the getUserName()
custom method, the method is returning the property and indirectly the same thing is happening. So, you don't need to use a method for this.
In both cases, the __get()
magic method is being triggered to return the item from the attributes array. Check about Magic Methods on PHP
manual.
In some cases, you may need to use a dynamic non-existing
property, for example, if you have a first_name
and last_name
field/property and you want to use both names together as a full_name
property then in this case, Laravel
provides a nice way to get it. All you need to do is that, create a method like:
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
So then, you may use {{ $user->full_name }}
to get that concatenated value.
There is no difference. You get exactly the same result in this case so this function won't be too helpful in this case. In above case you simply created function that returns one of field, but you could also create function that return 2 fields separated by comma:
public function getUserAge() {
return $this->username.', '.$this->age;
}
and then you could use
{{{ Auth::user()->getUserAge() }}}
in your view.
But you can also create accessor and mutators for your model attributes to change what you set/get from your model
Pretty much no difference, except adding a wrapper function for getting it via just by the attribute will add the overhead of an extra function call, which you don't need (thus minutely decreasing performance).
Getting an attribute (in your example by doing just $this->username
) will ultimately boil down to calling this function in Illuminate\Database\Eloquent\Model
:
/**
* Dynamically retrieve attributes on the model.
*
* @param string $key
* @return mixed
*/
public function __get($key)
{
return $this->getAttribute($key);
}
Wrapping this function call with your own is quite unnecessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With