title: How to add a dynamic appends to a model in Laravel
body: <p>To start, let me explain my DB schema.</p>
  
  <p>The important part for this question is I have 3 tables:</p>
  
  <ul>
  <li>components</li>
  <li>codes</li>
  <li>component_codes (that acts as a pivot table for the relationship between the two)</li>
  </ul>
  
  <p>Components and Codes are in a ManyToMany relationship.</p>
  
  <p>I've got restful API set up in the <code>/components/index/</code> route that looks like this:</p>
  
  <pre><code>  {
      "id": "49",
      "name": "Gloves",
      "thumb": "img\/product.jpg",
      "filter_id": "9",
      "active": "1",
      "created_at": "2014-01-10 17:45:00",
      "updated_at": "2014-01-10 17:45:00",
      "codes": [
        {
          "id": "4",
          "code": "asd123",
          "specs": "10x10cm",
          "packing": "100",
          "active": "1",
          "created_at": "2014-01-06 16:19:26",
          "updated_at": "2014-01-06 16:19:26",
          "pivot": {
            "component_id": "49",
            "code_id": "4"
          }
        }
    }
  </code></pre>
  
  <p>I now want to append two values to the "codes" child json object which will have the value of that object's parent. In this case, I need the "codes" array to have the value <code>"name": "Gloves"</code> and <code>"thumb": "img\/product.jpg"</code>. Essentially duplicating it's parent's data.</p>
  
  <p>So far I have this:</p>
  
  <p><strong>models/Code.php</strong></p>
  
  <pre><code>&lt;?php
  
  class Code extends Eloquent {
      protected $table = 'codes';
      protected $appends = array('parent_name', 'parent_img_url');
  
      protected $guarded = array();
  
      public static $rules = array();
  
      public function components()
      {
          return $this-&gt;belongsToMany('Component', 'component_codes', 'component_id', 'code_id');
      }
  
      public function getParentNameAttribute()
      {
          $parent = Component::find(50);
          return $parent-&gt;name_en;
      }
  
      public function getParentImgUrlAttribute()
      {
          $parent = Component::find(50);
          return $parent-&gt;thumb;
      }
  
  }
  </code></pre>
  
  <p>This works as expected, but it's not dynamic, the ID of the component is hard coded in (ie: 50). I need this to be the ID of the component in question.</p>
  
  <p>Hope I made myself clear, if not, please let me know in the comments.</p>
  
  <p><strong>Edit:</strong> Another solution would be to add those values to the pivot table laravel creates. Right now there's only the component_id and the code_id in it. If there's anyway to add a the component's name to it as well it would fit my needs.</p>