DEV Community

Discussion on: Export 10M+ rows in XLSX with Laravel without memory issues

Collapse
 
rahulprgrmr profile image
Rahul Raveendran

Showing Error: Can use "yield from" only with arrays and Traversables. Can you help?

Collapse
 
rap2hpoutre profile image
Raphaël Huchet • Edited

The method I wrote does not work with model, thank you for your feedback! I fixed the article using cursor which is simpler!

foreach (User::cursor() as $user) {
    yield $user;
}
Enter fullscreen mode Exit fullscreen mode

Still you could chunk by larger slices manually, like in this code:

// Generator function
function getUsersOneByOne() {
    // build your chunks as you want (200 chunks of 10 in this example)
    for ($i = 0; $i < 200; $i++) {
        $users = DB::table('users')->skip($i * 10)->take(10)->get();
        // Yield user one by one
        foreach($users as $user) {
            yield $user;
        }
    }
}

// Export consumes only a few MB
(new FastExcel(getUsersOneByOne()))->export('test.xlsx');
Enter fullscreen mode Exit fullscreen mode

Thank you!!