Saturday, March 18, 2017

Append custom attribute optionally/manually?

Following this in the docs:

https://laravel.com/docs/5.3/eloquent-serialization#appending-values-to-json

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

    public function getIsAdminAttribute()
    {
        return $this->attributes['admin'] == 'yes';
    }
}

Is it possible to manually append my custom attribute in a query?

There are certain situations where I don't need to have this information in my JSON, and I'd rather be able to manually append the custom attribute in a query, like:

$users = User::append('is_admin')
    ->get();

This obviously doesn't work, but I'm wondering if there is a way to do this.



via user7733152

Advertisement