Why use $appends with Accessors in Eloquent?

Eloquent has a convenient feature called Accessors - you can define your own custom fields on top of existing in the database table. But then there's an Eloquent property $appends - should we use it or not? And what's the difference?

First - how Accessors work

For those who don't know or have forgotten: for example, if you have User model and fields first_name and last_name in the DB table, then you can create a function in app\User.php:
function getFullNameAttribute() {
  return $this->first_name . ' ' . $this->last_name;
}
Then you have access to property full_name (in the function name it's CamelCase, and the property name is with underscores _), for example like this:
echo User::find(1)->full_name;
But here's the thing - if you just return User object, it won't contain full_name:
dd(User::find(1)->toJSON());
The result would look something like this:
{
  "id":1,
  "first_name":"Povilas",
  "last_name":"Korop",
  "email":"povilas@webcoderpro.com",
  "created_at":"2015-06-19 08:16:58",
  "updated_at":"2015-06-19 19:48:09"
}

Here's where $appends comes in

Now this is the trick - in your User model you can add $appends attribute and list the fields that would automatically be appended:
class User extends Model
{
  // ...
  protected $appends = ['full_name'];
Now that attribute will be automatically added to the previous JSON:
{
  "id":1,
  "first_name":"Povilas",
  "last_name":"Korop",
  "email":"povilas@webcoderpro.com",
  "created_at":"2015-06-19 08:16:58",
  "updated_at":"2015-06-19 19:48:09",
  "full_name":"Povilas Korop"
}
Want more articles like this every week? Subscribe!
Still not sure? Want to check out past newsletter issues? Here they are - just click this link!
So, in short - Accessor fields would work just by describing getAbcAttribute() methods, but if you want them to be returned in the list as well, then add them to $appends property. More about Accessors (and related - Mutators) - in the official documentation.

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 66 courses (1167 lessons, total 43 h 18 min)
  • 88 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses