How to always append attributes to Laravel Eloquent model? How to always append attributes to Laravel Eloquent model? laravel laravel

How to always append attributes to Laravel Eloquent model?


After some search I found that you simply need to add the attribute you wants to the $appends array in your Eloquent Model:

 protected $appends = ['user'];

Update: If the attribute exists in the database you can just use protected $with= ['user']; according to David Barker's comment below

Then create an Accessor as:

public function getUserAttribute(){    return $this->user();}

This way you always will have the user object for each post available as:

{    id: 1    title: "My Post Title"    body: "Some text"    created_at: "2-28-2016"    user:{            id: 1,            name: "john smith",            email: "example@mail.com"         }}


I found this concept is interesting, I learn and share things.Here in this example, I append id_hash variable which then converted into method by this logic, It takes first char and converts into upper case i.e. Id and letter after underscore to uppercase i.e. Hash.

Laravel itself add get and Attribute to combine all together it gives getIdHashAttribute()

class ProductDetail extends Model{    protected $fillable = ['product_id','attributes','discount','stock','price','images'];    protected $appends = ['id_hash'];    public function productInfo()    {        return $this->hasOne('App\Product','id','product_id');    }    public function getIdHashAttribute(){        return Crypt::encrypt($this->product_id);    }}

To simplify things append variable would be like this

protected $appends = ['id_hash','test_var'];

The method would be defined in the model like this

 public function getTestVarAttribute(){        return "Hello world!";    }