How To Append Values To JSON In Laravel With Example

admin_img Posted By Bajarangi soft , Posted On 10-09-2020

When building JSON APIs, you will often need to convert your models and relationships to arrays or JSON. Eloquent includes convenient methods for making these conversions, as well as controlling which attributes are included in your serializations and when casting models to an array or JSON, you may wish to add attributes that do not have a corresponding column in your database.so today we are going to discuss how to append values to json in laravel

How To Append Values To JSON In Laravel With Example

Appending Values To JSON

To do so, first define an accessor for the value:

Open User.php model file and implement code as below

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
   
    public function getIsAdminAttribute()//is_admin is the function
    {
        return $this->attributes['admin'] === 'yes';
    }
}
 

After creating the accessor, add the attribute name to the appends property on the model.

Note that attribute names are typically referenced in "snake case", even though the accessor is defined using "camel case":

 

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['is_admin'];
}


Once the attribute has been added to the appends list, it will be included in both the model's array and JSON representations.

Attributes in the appends array will also respect the visible and hidden settings configured on the model.


Appending At Run Time

You may instruct a single model instance to append attributes using the append method. Or, you may use the setAppends method to override the entire array of appended properties for a given model instance:

return $user->append('is_admin')->toArray();

return $user->setAppends(['is_admin'])->toArray();

Related Post