title: Casting Eloquent\Collection (Laravel) to stdClass array using Repository pattern
body: <p>I'm trying to implement the Repository pattern in a <strong>Laravel 5</strong> app by following <a href="http://dfg.gd/blog/decoupling-your-code-in-laravel-using-repositiories-and-services" rel="nofollow">this article</a>. In it, the repository implementation converts the object for the specific data source (in this case Eloquent) to an stdClass so that the app uses a standard format and doesn't care about the data source. </p>
  
  <p>To convert a single Eloquent object they do this:</p>
  
  <pre><code>/**
  * Converting the Eloquent object to a standard format
  * 
  * @param mixed $pokemon
  * @return stdClass
  */
  protected function convertFormat($pokemon)
  {
      if ($pokemon == null)
      {
          return null;
      }
  
      $object = new stdClass();
      $object-&gt;id = $pokemon-&gt;id;
      $object-&gt;name = $pokemon-&gt;name;
  
      return $object;
  }
  </code></pre>
  
  <p>Or, as someone in the comments pointed out, this could also work: </p>
  
  <pre><code>protected function convertFormat($pokemon)
  {
      return $pokemon ? (object) $pokemon-&gt;toArray() : null;
  }
  </code></pre>
  
  <p>But then, what happens when <strong>I want to cast an entire collection of Eloquent objects to an array of ** <code>stdClass</code> **? Do I have to loop through the collection and cast each element separately?</strong> I feel this would be a big hit on performance, having to loop and cast every element every time I need a collection of something and it also feels dirty.</p>
  
  <p>Laravel provides <code>Eloquent\Collection::toArray()</code> which turns the entire collection to an array of arrays. I suppose this is better, but still not <code>stdClass</code></p>
  
  <p>The benefits of using a generic object would be that I could do this in my code </p>
  
  <pre><code>echo $repo-&gt;getUser()-&gt;name;
  </code></pre>
  
  <p>Instead of having to do this:</p>
  
  <pre><code>echo $repo-&gt;getUser()['name'];
  </code></pre>