How to append new attributes to eloquent model Adding new attribute to model when converted into array or json

Here we will see how we can add a new attribute in an eloquent model.

Sometimes When converting models to arrays or JSON,we require additional information based on some calculation/manipulation on columns of models, in that case we can easily add this new attribute in model using following steps provided by Laravel.

Suppose we have an user model and we want a full_name attribute to be appended for the user. As first_name and last_name already exist in database as columns  ,we can easily create fullname as following:

1. Define Accessor :


<?php
 
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
 
class User extends Model
{
    /**
     * Determine  full name of user
     *
     * @return \Illuminate\Database\Eloquent\Casts\Attribute
     */
  public function getFullNameAttribute()
    {
        return $this->first_name . ' ' . $this->last_name;
    }
}

If we only define accessor we can refer user full_name using following code

Livewire Component Library
 User::find(1)->full_name;

But here’s the thing – if you just return User object, it won’t contain full_name:

Host Laravel Application on DigitalOcean

Use coupon 5balloons on this Cloudways Affiliate URL to get special discount.

dd(User::find(1)->toJSON());

The result would look something like this:

{
  "id":1,
  "first_name":"abc",
  "last_name":"def",
  "created_at":"2022-06-19 08:16:58", 
  "updated_at":"2022-06-19 19:48:09"
}

So here comes the next step :

2. Add attribute to Append property:


<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class User extends Model
{
    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['full_name'];
}

Note that attribute names are typically referenced using their “snake case” (full_name) serialized representation, even though the accessor’s PHP method is defined using “camel case”(getFullNameAttribute).

Once the attribute has been added to the appends list, it will be included in both the model’s array and JSON representations, like following :

{
  "id":1,
  "first_name":"abc",
  "last_name":"def", 
  "created_at":"2022-06-19 08:16:58",
  "updated_at":"2022-06-19 19:48:09",
  "full_name":"abc def"
}

Site Footer