title: Laravel presenters for JSON responses
body: <p>I’ve recently discovered that presenters (<a href="https://github.com/ShawnMcCool/laravel-auto-presenter" rel="nofollow">like this one</a>) implement the <a href="http://en.wikipedia.org/wiki/Decorator_pattern" rel="nofollow">decorator pattern</a> and are a great way to add fields and logic to existing Laravel models. Take the following example for my question below:</p>
  
  <pre><code>// Tack on a new readable timestamp field.
  public function timeago()
  {
      return $this-&gt;object-&gt;created_at-&gt;whenForHumans();
  }
  
  // Wrap an existing field with some formatting logic
  public function created_at()
  {
      return $this-&gt;object-&gt;created_at-&gt;format('Y-m-d');
  }
  </code></pre>
  
  <p>I can then use these presenter fields in my view:</p>
  
  <pre><code>{{ $object-&gt;timeago }}
  {{ $object-&gt;created_at }} 
  </code></pre>
  
  <p><strong>How would you implement the decorator pattern for an API that returns JSON responses rather than Blade views?</strong> In all the Laravel/JSON articles I have read, objects are immediately returned without undergoing any transformation / presenter logic. e.g.:</p>
  
  <pre><code>// converting a model to JSON
  return User::find($id)-&gt;toJson();
  
  // returning a model directly will be converted to JSON
  return User::all();
  
  // return associated models
  return User::find($id)-&gt;load('comments')-&gt;get();
  </code></pre>
  
  <p>How can I implement presenter fields in my JSON response?</p>
  
  <pre><code>$object-&gt;timeago
  $object-&gt;created_at
  </code></pre>