Laravel CSV导入 - 我可以使用请求验证吗?

时间:2018-06-08 16:36:17

标签: php laravel csv validation request-validation

我正在使用Laravel 5.6并为我的表单设置form request validation,它提交单行,验证它然后添加到数据库。一切正常。

对于多行的批量导入,我有一个CSV导入。 CSV被解析为一个数组,然后数组的每一行包含与我的表单中提供的数据类型完全相同的数据,因此可以使用相同的验证规则。

我有点迷失了如何将数据实际实现为数据,一旦从CSV中解析出来就是数组,而不是表单验证请求正在寻找的请求对象。

有没有人提供关于在不重复代码的情况下对表单和CSV使用表单验证的最佳方法的任何提示?

修改

如果有人有兴趣,我的最终解决方案是不使用表单请求验证。在我的例子中,将验证规则和消息添加到控制器内的某些受保护功能更容易。这意味着它们可以在需要它的每个控制器函数(store,csvStore等)中重复使用,而无需重复代码。在这种情况下,我不确定表单请求验证功能给出了什么优势。

//reformat CSV into array
$master = [];
$line_id = 1;
foreach ($data as $row) {
    //skip blank rows
    if (empty($row['sku'])) continue;
    //build master
    foreach($row as $key => $value){
        if(!empty($value)) $master[$row['sku']][$key] = $row[$key];
    }
    //add line number for debugging
    $master[$row['sku']]['line_number'] = $line_id;
    $line_id++;
}

//Validate each row of CSV individually
$error_messages = new MessageBag();
$error_count = 0;
$duplicate_count = 0;
if(empty($master)){
    //empty $master
    $error_messages->add('', 'CSV file does not contain valid data or is empty');
    flash()->message('Nothing was imported');
    return redirect()->back()->withErrors($error_messages);
} else {
    foreach($master as $row){
        $validator = Validator::make($row,$this->createValidationRules(), $this->createValidationMessages());

        //Check validation
        if ($validator->fails()){
            $master[$row['sku']]['valid'] = false;
            if(isset($validator->failed()['sku']['Unique'])){
                $duplicate_count ++;
                if(!request('ignore-duplicates') && !request('ignore-errors')) $error_messages->merge($validator->errors()->messages()); //save error messages
            } else {
                $error_count ++;
                if(!request('ignore-errors')) $error_messages->merge($validator->errors()->messages()); //save error messages
            }
        } else {
            $master[$row['sku']]['valid'] = true;
        }
    }
}

//add successful rows to DB
$success_count = 0;
foreach($master as $row){
    if($row['valid'] == true){
        $productCreate = new ProductCreate();
        $productCreate->create($row);
        $success_count++;
    }
}

然后我使用成功/错误/重复计数发送回合适的错误消息包和/或flash消息。

1 个答案:

答案 0 :(得分:1)

您可以通过创建Request对象宏来将CSV转换为数组,然后使用中间件来解析传入请求(如果它是csv文件并将其合并到传入请求中)。然后,您的应用程序验证可以使用数组验证对其进行验证。

首先让服务提供商存放您的请求宏:

php artisan make:provider RequestMacroParseCsvProvider

然后在服务提供商中:

在顶部添加此项以获取Request类:

use Illuminate\Http\Request;

在提供者的注册方法中:

Request::macro('parseCsv', function ($fileNameKey) {
    // Note: while working inside of the request macro closure, you can access the request object by referencing $this->{key_of_request_item}

    // You will be running your parser against $fileNameKey which will be the key of the request file coming in. So you'd access it like:
    if ($this->hasFile($fileNameKey)) {
        // Your code to parse the csv would go here. Instantiate your csv parsing class or whatever...
        // $file = $this->file($fileNameKey);
        // Store the parsed csv in an array, maybe named $parsedCsv?
    }

    return empty($parsedCsv) ? [] : $parsedCsv;
});

config/app.php

中注册服务提供商

App\Providers\RequestMacroParseCsvProvider::class,

创建中间件以检查传入请求是否包含csv

php artisan make:middleware MergeCsvArrayIntoRequest

handle方法中:

if ($request->has('your_csv_request_key)) {
    $parsedCsv = $request->parseCsv('your_csv_request_key');

    // Then add it into the request with a key of 'parsedCsv' or whatever you want to call it
    $request->merge(['parsedCsv' => $parsedCsv]);
}

return $next($request);

app/Http/Kernel.php

中注册您的中间件
protected $middleware = [
    ...
    \App\Http\Middleware\MergeCsvArrayIntoRequest::class,
    ...
];

如果您不希望它是全球性的,请将其放入$routeMiddleware

'parse.csv' => \App\Http\Middleware\MergeCsvArrayIntoRequest::class,

现在,您的中间件正在拦截并转换您上传的所有CSV文件,您可以使用Laravel的array validation验证parsedCsv请求密钥。

如果您愿意,您绝对可以进行一些改进以使其更加灵活。我在另一个项目中做了类似的事情,但文档不太相关,我需要在我的控制器验证之前修改请求并且它有效。

希望这有帮助。