title: Laravel loop through query result, then paginate
body: <p>I'm working on an event booking system. When the user searches for a date range, I use a function inside my <code>Event</code> model that checks if the event is available. My search function currently works as follows:</p>
  
  <pre><code>    $events = Event::where('name', 'LIKE', '%' . $request-&gt;get('term') . '%')
          -&gt;where('accepted',1)
          -&gt;orWhere('description', 'LIKE', '%'.$request-&gt;get('term').'%')
          -&gt;orWhere('city', 'LIKE', '%'.$request-&gt;get('term').'%')-&gt;paginate(15);
  
      $availableEvents = new Collection();
  
      if ($request-&gt;get('from') !== '' AND $request-&gt;get('to') !== '') {
          foreach($events as $key =&gt; $event) {
              if ($event-&gt;is_available($request-&gt;get('from'), $request-&gt;get('to'))) {
                  $availableEvents-&gt;add($event);
              }
          }
      }
      else {
          $availableEvents = $events;
      }
  
      return view('frontend.events.results', ['events' =&gt; $availableEvents, 'request' =&gt; $request]);
  </code></pre>
  
  <p>I can't check availability inside the query builder so I have to loop through. I'm using a <code>Illuminate\Database\Eloquent\Collection</code> because I can't remove events from the paginated thing I get from the query builder.</p>
  
  <p>Is there some way to convert the Eloquent Collection to a paginated collection? </p>
  
  <p>Thanks in advance!</p>
  
  <p>P.S. I'm passing <code>$request</code> to the view to use <code>appends()</code> so I can retain the query string parameters during pagination.</p>
  
  <p>EDIT: The <code>is_available</code> function</p>
  
  <pre><code>public function is_available($from, $to) {
  
      $from = Carbon::createFromFormat('d-m-Y', $from);
      $to = Carbon::createFromFormat('d-m-Y', $to);
  
      foreach($this-&gt;not_availables as $notAvailable) {
  
          $notAvailableFrom = Carbon::createFromFormat('Y-m-d', $notAvailable-&gt;from);
          $notAvailableTo = Carbon::createFromFormat('Y-m-d', $notAvailable-&gt;to);
  
          if ($from-&gt;gte($notAvailableFrom) OR $to-&gt;lte($notAvailableTo)) {
              return false;
          }
      }
  
      return true;
  }
  </code></pre>