How to chunk results from a custom query in Laravel
The chunk
feature is only available for Eloquent models and QueryBuilder requests, e.g.
DB::table('tbl')->where('num', '>', 3)->chunk(500, function($rows) {
// process $rows
});
But it won't work for DB::select('...')
request.
You need to either use a QueryBuilder request, or use an underlying PDO object to query the database, e.g:
$pdo = DB::getPdo();
$sth = $pdo->prepare("SELECT ....");
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC))
{
// ...
}
Try something like this:
<?php
$max = 100;
$total = DB::connection('legacy')->select("...")->count();
$pages = ceil($total / $max);
for ($i = 1; $i < ($pages + 1); $i++) {
$offset = (($i - 1) * $max);
$start = ($offset == 0 ? 0 : ($offset + 1));
$legacy = DB::connection('legacy')->select("...")->skip($start)->take($max)->get();
/* Do stuff. */
}
Basically duplicates what Laravel's Paginator does without the extra overhead.