Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Cryank's avatar

Questions about User::Chunk()

Hello Everyone,
It looks that to deal with thousand of records it may good to chunk result instead of using all().
therefore I change my code to

       $users = collect();
        \App\UserExport::chunk(500,function($rs) use ($users){
            foreach($rs as $record)
            {
                $users->push($record);
            }
        });
        return $users;

However, how can i do the same thing with some conditions like

       // find user who belongs to specific 'role'
      \App\UserExport::whereHas('role', function($q) use($role)
        {
            $q->where('slug', '=', $role);

        })->get();

// using Scope 
  \App\UserExport::GraduatedInYearOnly($year)->get();

    public function scopeGraduatedInYearOnly($query,$year){
        $query->where('graduation_year', $year);
    }

By the way, I would like to know how you guys handling large-data for export
I am using laravel excel, It costs about 13~15sec to export ~1000 rows of records.

// this toArray() function needs about 4 - 5s for 1000 rows 
  foreach($users as $record)
        {
            $_user = $record->toArray();
             ....
       }

 //  sheet create costed about 6 secs 
    Excel::create('export', function($excel) use($exportFields,$exportUsers){

            $excel->sheet('export', function($sheet) use($exportFields,$exportUsers) {
                $sheet->fromArray(array_merge(array($exportFields),$exportUsers), null, 'A1', false, false);
            });

        })->export('xls');
0 likes
1 reply
jekinney's avatar

Set up your query as normal then chunk the collection.

That's not to bad for an export. I know data tables js breaks after a 1000. Meaning you could take a nap while waiting.

Please or to participate in this conversation.