Laravel Pagination with hydrated Model collection
<p>I have a Laravel 5.2 application which interacts with a database that has a pretty free-form schema. I have one particularly gnarly query that has not yet been converted into Eloquent syntax, instead we are stuck with <code>hydrateRaw</code> for the time being:</p>

<pre><code>&lt;?php                                                                                                                                                                                                                                                            

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
...

class MyModel extends Model
{
    /** 
     * Do some crazy stuff to get a MyModel Collect
     *
     * @params so many
     * @return Collection
     */
    public static function getModels($param1, $param2, $param3, $limit)
    {   
        return static::hydrateRaw("SELECT table1.id, table2.name, table3.date from...", [$param1, $param2, $param3, $limit]);
    }
    ...
}
</code></pre>

<p>I have tried a number of different methods to shoehorn this collection into a <code>LengthAwarePaginator</code>, with partial success.</p>

<p>If I have this in the Controller:</p>

<pre><code>$models = MyModel::getModels(1,2,3,1000);
$paginated = new LengthAwarePaginator($models, $models-&gt;count(), 12, 2);
</code></pre>

<p>And have a view like:</p>

<pre><code>@foreach ($paginated as $model)
    {{ $model-&gt;name }}
@endforech
</code></pre>

<p>I get the whole collection (no pagination), although methods like <code>currentPage()</code> work correctly.</p>

<p><a href="https://laravel.com/docs/5.2/pagination#manually-creating-a-paginator" rel="nofollow">The docs</a> cryptically hint at using <code>array_slice</code> however I'm not sure what to do with it. If I call <code>$models-&gt;toArray()</code> I may as well have not hydrated the models (which is a nuisance because I was hoping to cache as much as possible).</p>

<p>I've jury rigged a solution that I've posted below, but I would really like to know if I can get pagination to just work because I'm going to run into this situation a few more times, would like to keep as much logic out of the views as possible, and just have a feeling a little tweak could get this to work.</p>