Search code examples
phplaravellaravel-5

How to always append attributes to Laravel Eloquent model?


I was wondering how to always append some data to Eloquent model without the need of asking for it for example when getting Posts form database I want to append the user info for each user 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"
         }
}

Solution

  • 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"
             }
    }