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

aavinseth's avatar

Maatwebsite excel AfterImport

How to access the array which I have created as default in afterImport function of Maatwebsite excel.

Below is my code

<?php

namespace App\Imports;


use DateTime;
use Illuminate\Contracts\Queue\ShouldQueue;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\RegistersEventListeners;
use Maatwebsite\Excel\Events\AfterImport;

class ProductToStoreImport implements ToCollection, WithHeadingRow, WithBatchInserts, WithChunkReading, ShouldQueue, WithEvents
{
    private $rows = 0; // intialize row count
    public $data = [];
    public $finaldata = [];
    use Importable, RegistersEventListeners;

    private $store_id;
    function __construct($store_id)
    {
        $this->store_id = $store_id;
        $this->data['unused_product'] = [];
    }

    public function collection(Collection $rows)
    {
        try {
            foreach ($rows as $key => $row) {
                if ($row->filter()->isNotEmpty()) {
                    ++$this->rows; // increment row count
                    $validator = Validator::make($row->toArray(), $this->rules(), $this->validationMessages());
                    if ($validator->fails()) {
                        $rowerror = collect($validator->errors())->map(function ($item) {
                            return $item;
                        })->flatten()->all();
                        $row->put('error', collect($rowerror)->implode(', '));
                        $this->data['unused_product'][] = $row;
                    } else {
                        if ($row['price'] == 0) {
                            $row->put('error', 'Price is ZERO');
                            $this->data['unused_product'][] = $row;
                        }
                    }
                }
            }

            $this->finaldata[] = $this->data['unused_product'];
            Log::info('Process finish');
        } catch (Exception $e) {
            Log::debug($e->getMessage());
        }
    }

    public function headingRow(): int
    {
        return 1;
    }

    public function getRowCount(): int
    {
        return $this->rows; 
    }

    public function batchSize(): int
    {
        return 2000;
    }

    public function chunkSize(): int
    {
        return 2000;
    }

    public static function afterImport(AfterImport $event)
    {
        // Need to access $finaldata here and send mail to user
        Log::info('after import excel file');
    }

    // this function returns all validation errors after import:
    public function getErrors()
    {
        return $this->errors;
    }

    public function rules(): array
    {
        return [
            'short_item_no' => 'required',
            'barcode' => 'required',
            'description' => 'required',
            'quantity' => 'required',
            'barcode_uom' => 'required',
            'price' => 'required',
            'tax_rate' => 'required',
            'section' => 'required',
            'sub_sections' => 'required',
        ];
    }

    public function validationMessages()
    {
        return [
            'short_item_no.required' => 'Short Item No is required',
            'barcode.required' => 'Barcode is required',
            'description.required' => 'Description is required',
            'quantity.required' => 'Quantity is required',
            'barcode_uom.required' => 'Barcode UOM is required',
            'price.required' => 'Price is required',
            'tax_rate.required' => 'Tax Rate is required',
            'section.required' => 'Section is required',
            'sub_sections.required' => 'Sub Sections is required',
        ];
    }
}
0 likes
3 replies
kobi4's avatar

Did you succeed in the end?

I in same issue

1 like
different's avatar

Like this:

public function registerEvents(): array
{
    return [
        AfterImport::class => function(AfterImport $event) {
            dump($this->finaldata)
        },
    ];
}
vicodeveloper's avatar

For Sheet you need use like this example:

public function registerEvents(): array
    {
        return [
            // Array callable, refering to a static method.
            // AfterImport::class => [self::class, 'afterImport'],
            AfterSheet::class => [self::class, 'afterSheet'],
        ];
    }

    public static function afterSheet(AfterSheet $event)
    {
        $import = $event->getConcernable();
        foreach ($import->customerItem as $customerId => $data) {
            $users = User::where('some_id', $customerId)->get();
            Notification::send($users, new ItemsImportedNotification(
                collect($data['items']),
                $data['total']
            ));
        }
    }

Please or to participate in this conversation.