title: How can I paginate an array of objects in Laravel?
body: <p>I'm building an application using Laravel 4.2. I have a model for <code>units</code> and another for <code>users</code> and pivot table <code>user_units</code>. Every user in this application can select a unit and add it to his favorite list then he can publish this unit with his information as an ad. </p>
  
  <p>I want to select all units published by all users </p>
  
  <p>The <code>user_units</code> (pivot) table has the following columns:</p>
  
  <pre><code>id   
  user_id 
  unit_id 
  publish      
  adtype       
  addinfo          
  created_at  
  updated_at
  </code></pre>
  
  <p>With relations methods on models</p>
  
  <pre><code>public function users() {
      return $this-&gt;belongsToMany('User', 'user_units')
                  -&gt;withPivot('id','publish', 'adtype', 'addinfo');
  }
  
  public function units() {
      return $this-&gt;belongsToMany('Unit', 'user_units')
                  -&gt;withPivot('id','publish', 'adtype', 'addinfo');
  }
  </code></pre>
  
  <p>My query to select all published units by all users</p>
  
  <pre><code>// Get all published units by users for sale. 
      $users = User::all();
      $publishedSaleUnits = [];
      foreach($users as $user){
          $userUnits = $user-&gt;units()-&gt;orderBy('adtype', 'desc')-&gt;get();
          if(count($userUnits)){
              foreach($userUnits as $unit){
                  if($unit-&gt;pivot-&gt;publish == 1 &amp;&amp; $unit-&gt;unit_purpose_id == 1){
                      if( $unit-&gt;pivot-&gt;adtype ){
                          //push all featured ads onto the beginning of array
                          array_unshift($publishedSaleUnits, $unit);
                      }else{
                          //push all normal ads onto the end of array
                          array_push($publishedSaleUnits, $unit);
                      }
                  }
              }
          }
      }
  </code></pre>
  
  <p>Now I got the result but I can't use pagination with results because it's an array of objects.</p>
  
  <p>So is there any better solution to get all published units by user with pagination?</p>