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);
}
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'],
]);
}
}
Most helpful comment
I found
WithMappingconcern which hasmapfunction with the same purpose, but it's not documented onImportssection.