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();