Michał Śnieżko
Michał Śnieżko

Reputation: 155

What's the difference between $model->foo and $model->getAttributeValue('foo')?

When I have an instance of Eloquent model called $model I can retrieve a value of its attribute (for example name of an user) in two ways:

$name = $user->name;

or

$name = $user->getAttributeValue('name');

Which way is correct and what is the difference between those two ways of retrieving a value?

Upvotes: 3

Views: 720

Answers (1)

Camilo
Camilo

Reputation: 7194

When you call a model attribute,

  • First the __get() method is called.
  • Then the getAttribute() method is called.
  • And finally getAttributeValue() or getRelationValue() is called.

So, it's basically the same using a property or getAttributeValue() to get a model attribute. Just keep in mind that it can't access model relationships.

Let's note that most (or all?) of the Laravel documentation uses properties to access a model attributes.

Upvotes: 2

Related Questions