anonymouse703's avatar

How to log summary of total rows imported instead of each value?

I have this importer, on manual input I have log and it's ok but on import I only want to store total rows imported I tried this but still each row is logged

   public function afterImport(Import $import): void
    {
        $success = $import->successful_rows;
        $failed = $import->getFailedRowsCount();

        activity()
            ->causedBy(Auth::user())
            ->event('import')
            ->withProperties([
                'successful_rows' => $success,
                'failed_rows' => $failed,
            ])
            ->log("Guest import completed: {$success} successful, {$failed} failed");
    }

this is my whole import

1 like
3 replies
vincent15000's avatar

Perhaps you should add a counter inside this function.

	public $counter = 0;

    public function resolveRecord(): Guest
    {
		$this->counter = $this->counter + 1;

        return Guest::firstOrNew([
            'name' => data_get($this->data, 'name'),
        ]);
    }

And add a getter function to return the counter value.

But I don't understand how you can access the $this->data variable, it's not declared in the class and not passed to the function. Perhaps from the Importer class ?

Tray2's avatar

Just a quick tip

$this->counter = $this->counter + 1;

Can be written like

$this->counter++;

Which I think is way cleaner.

anonymouse703's avatar
anonymouse703
OP
Best Answer
Level 6

Thanks sir, I solved it like this

public static function getCompletedNotificationBody(Import $import): string
    {
        activity()->enableLogging();

        $successfulRows = $import->successful_rows;
        $failedRowsCount = $import->getFailedRowsCount();

        activity()
            ->causedBy(Auth::user())
            ->event('import')
            ->withProperties([
                'successful_rows' => $successfulRows,
                'failed_rows' => $failedRowsCount,
            ])
            ->performedOn(new Employee())
            ->log("Employee import completed: {$successfulRows} successful, {$failedRowsCount} failed");

        $body = 'Your employee import has completed and ' . Number::format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.';

        if ($failedRowsCount = $import->getFailedRowsCount()) {
            $body .= ' '.Number::format($failedRowsCount).' '.str('row')->plural($failedRowsCount).' failed to import.';
        }

        return $body;
    }

Please or to participate in this conversation.