3

I have model something like that with custom attribute

class MyModel extends Model
{
    public function getExtraAttribute(){
        return 'some string'; //etc.
    }
}

And for controller method i have this

return MyModel::where('user_id', Auth::user()->id)->get();

But i don't see 'extra' attribute on json response

P.s. extra isn't column from database.

2 Answers 2

10

Add the attribute to $appends.

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

As per the docs here: https://laravel.com/docs/5.4/eloquent-serialization#appending-values-to-json

class User extends Model
{
     protected $appends = ['extra'];

     public function getExtraAttribute()
     {
        return $this->attributes['extra'] = 'some string...';
     }
}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.