PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, April 19, 2022

[FIXED] How to always append attributes to Laravel Eloquent model?

 April 19, 2022     api, laravel, laravel-5, php, restful-architecture     No comments   

Issue

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


Answered By - Mustafa Dwekat
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing