Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[QUESTION] How to manipulate row values before validation? #2359

Closed
4 tasks done
hafezd opened this issue Sep 9, 2019 · 1 comment
Closed
4 tasks done

[QUESTION] How to manipulate row values before validation? #2359

hafezd opened this issue Sep 9, 2019 · 1 comment
Labels

Comments

@hafezd
Copy link

hafezd commented Sep 9, 2019

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);
}
@hafezd hafezd added the question label Sep 9, 2019
@hafezd
Copy link
Author

hafezd commented Sep 9, 2019

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'],
        ]);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant