Laravel - different methods to access a model attribute

Viewed 462

i found out there are several ways to access a model attribute:

// In Model Class 1.
public function getUsername()
{
    return $this->username;
}

// OR 2.
public function getUsername()
{
    return $this->attributes['username'];
}

and then calling methods,

or just simply call the attribute when needed:

// 3.
$user->username;

What is the difference between these 3 methods? and which to use? best practice, performance and OOP?

1 Answers

The first two are correct from the point of view of OOP, because for those who use the object it should not matter how the object does to return the value to you. In the end, this Laravel mechanism points to the same variable and the implementation is almost the same.

But the third one is wrong since it accesses the attribute directly, because if you need to change the value format in the future, it would be much simpler to deal with this when returning the method.

Related