Search code examples
laravellaravel-5laravel-excel

Could I change row before saving Laravel Excel?


I use Laravel Excel.

The code builds excel file and does export to path $path.$filename:

  Excel::store(new VisitorsExport($request), $path.$filename);

Could I iterate all rows before Excel::store?


Solution

  • You can add WithMapping to your export so you can define a map() function that accept a row and return an array, so you can iterate and trasform all of your rows, this is an example with the Eloquent query builder:

    use Maatwebsite\Excel\Concerns\FromQuery;
    use Maatwebsite\Excel\Concerns\WithMapping;
    
    class VisitorsExport implements FromQuery, WithMapping
    {    
    
        public function map($visitor): array
        {
            return [
                $visitor->id,
                $visitor->name,
                Date::dateTimeToExcel($visitor->created_at),
            ];
        }
    }
    

    You can read the complete docs on mapping here.