[LARAVEL] code to retrieve million row in laravel - fourslickz/notes GitHub Wiki

use App\Models\YourModel;

$pageSize = 1000; // Number of rows to retrieve per page

// Disable query log to reduce memory usage
DB::connection()->disableQueryLog();

// Get the total number of rows
$totalRows = YourModel::count();

// Enable pagination
$records = YourModel::paginate($pageSize);

$records->onEachSide(0); // Disable pagination links

$currentPage = 1;

// Process each page
while ($currentPage <= $records->lastPage()) {
    // Retrieve the records for the current page
    $chunk = YourModel::whereBetween('id', [$records->firstItem(), $records->lastItem()])->get();

    // Process the chunk of records
    foreach ($chunk as $record) {
        // Process each record as needed
        echo $record->id;
    }

    // Move to the next page
    $records = YourModel::paginate($pageSize, ['*'], 'page', ++$currentPage);
}