Laravel-excel: [QUESTION] How to manipulate row values before validation?

Created on 9 Sep 2019  路  1Comment  路  Source: Maatwebsite/Laravel-Excel

Prerequisites

Versions

  • PHP version: 7.3.6
  • Laravel version: 5.8.33
  • Package version: 3.1.15

Description

Is there any way to manipulate data before validation? I have to trim strings and convert empty strings to null before validation.

Laravel has \Illuminate\Foundation\Http\Middleware\TrimStrings and \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull middlewares.

I think we should add something like prepareForValidation function on withValidation trait or define a new trait with a function to be invoked after reading the row and before validation.

/**
* Prepare row value for validation.
* 
* @param array          $rows
* @return array
*/
public function manipulateRow(array $row): array
{
    return array_map('trim', $row);
}
question

Most helpful comment

I found WithMapping concern which has map function with the same purpose, but it's not documented on Imports section.

use Maatwebsite\Excel\Concerns\WithMapping;

class UsersImport implements ToModel, WithMapping
{
    /**
     * @param mixed $row
     *
     * @return array
     */
    public function map($row): array
    {
        return array_map('trim', $row);
    }

    public function model(array $row)
    {
        return new User([
            'name' => $row['name'],
            'email' => $row['email'],
        ]);
    }
}

>All comments

I found WithMapping concern which has map function with the same purpose, but it's not documented on Imports section.

use Maatwebsite\Excel\Concerns\WithMapping;

class UsersImport implements ToModel, WithMapping
{
    /**
     * @param mixed $row
     *
     * @return array
     */
    public function map($row): array
    {
        return array_map('trim', $row);
    }

    public function model(array $row)
    {
        return new User([
            'name' => $row['name'],
            'email' => $row['email'],
        ]);
    }
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

ellej16 picture ellej16  路  3Comments

octoxan picture octoxan  路  3Comments

vandolphreyes picture vandolphreyes  路  3Comments

amine8ghandi8amine picture amine8ghandi8amine  路  3Comments

lucatamtam picture lucatamtam  路  3Comments