get data after save excel file with `maatwebsite/excel`

Viewed 34

Project in Laravel (9), and PHP (8.1).

I want to import an excel file and use maatwebsite/excel (3.1) package.

I can import a file, and save the file into the model, like this:

import class:

class BankTransfersHistoryImport implements ToModel, WithHeadingRow, WithValidation
{
    use Importable;

/**
 * @param array $row
 *
 * @return \Illuminate\Database\Eloquent\Model|null
 */
    public function model(array $row)
    {
        return new BankTransfersHistory([    
            'loanId' => $row['loanId'],
            'actionDate' => transformDate($row['actionDate']),
            'worth' => $row['worth'],
            .
            .
        ]);
    }

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

    public function rules(): array
    {
        return [ 
            '*.loanId' => ['required', 'numeric'],
            ... some roles ...
        ];
    }
}

controller:

        $import = new BankTransfersHistoryImport;

        try {
            // date validation
            $collection = $import->toCollection($file);
            ... some validation about the date ...

            $import->import($file);
            ... check and update rows ...

            return [
                "message" => some message,
                "data" => [
                    some data
                ],
            ];

        } catch (\Maatwebsite\Excel\Validators\ValidationException$e) {
            $failures = $e->failures();

            foreach ($failures as $failure) {
                $failure->row(); // row that went wrong
                $failure->attribute(); // either heading key (if using heading row concern) or column index
                $failure->errors(); // Actual error messages from Laravel validator
                $failure->values(); // The values of the row that has failed.
            }
            return $failures;
        }

My question is:

If I can get the response of the file after saving the data, and that will give me the data with the id of the row that was saved.

In some cases, I will have to update a row. That's why I would like to get the ID.

Now in the check and update rows section, I update by loanId + actionDate. I want it to be done by ID.


something like this:

code: $data = $import->import($file);

data will be like:

[
    {
        "id": 1,
        "loanId": 21001,
        "actionDate": "2020-01-02T00:00:00.000000Z",
        "worth": 2997.09,
        "offerId": 1,
    },
    {
        "id": 2,
        "loanId": 21002,
        "actionDate": "2020-01-02T00:00:00.000000Z",
        "worth": 3000,
        "offerId": 10,
    },
]
1 Answers

You can create a function on import class which will return the imported data, adding a sample for your reference.

UsersImport.php

<?php

namespace App\Imports;

use App\Models\User;
use Maatwebsite\Excel\Concerns\ToModel;

class UsersImport implements ToModel
{
    private $rows;

    public function __construct() {
        $this->rows = collect();
    }

    /**
     * @param array $row
     *
     * @return User|null
     */
    public function model(array $row)
    {
        $user = new User([
            'name'     => $row[0],
            'email'    => $row[1],
            'password' => bcrypt(12345678),
        ]);

        $this->rows->push($user);
        return $user;
    }

    /**
     * Returns Imported Data
     *
     * @return \Illuminate\Support\Collection
     */
    public function getImportedData(): \Illuminate\Support\Collection
    {
        return $this->rows;
    }
}

Your Import Function in Controller

public function import(UsersImport $usersImport)
{
    Excel::import($usersImport, public_path('users.xlsx'));
    $usersImport->getImportedData();
}
Related