【问题标题】:Per row validation while importing CSV file导入 CSV 文件时的每行验证
【发布时间】:2021-06-18 21:29:06
【问题描述】:

我正在将 CSV 文件导入到 livewire 组件并尝试对文件的每一行运行一些验证,但我在执行此操作时遇到了问题。看来我的验证什么也没做。

这是我的 Livewire 组件的样子:

namespace App\Http\Livewire\Modals;

use Validator;
use Livewire\Component;
use App\Http\Traits\Csv;
use App\Models\AccountUser;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Auth;

class ImportExtensions extends Component
{

use WithFileUploads;

public $clientID;
public $showModal = false;
public $upload;
public $columns;
public $fieldColumnMap = [
    'first_name' => '',
    'last_name' => '',
    'email' => '',
    'password' => '',
    'extension' => '',
    'user_type' => '',
];

protected $rules = [
        'fieldColumnMap.first_name' => 'required|max:255',
        'fieldColumnMap.last_name' => 'required|max:255',
        'fieldColumnMap.email' => 'required|max:255',
        'fieldColumnMap.password' => 'required|max:255',
        'fieldColumnMap.extension' => 'required|max:255',
        'fieldColumnMap.user_type' => 'required|max:255',
];

protected $validationAttributes = [
    'fieldColumnMap.first_name' => 'First Name',
    'fieldColumnMap.last_name' => 'Last Name',
    'fieldColumnMap.email' => 'Email',
    'fieldColumnMap.password' => 'Password',
    'fieldColumnMap.extension' => 'Extension',
    'fieldColumnMap.user_type' => 'User Type',
];

public function updatingUpload($value)
{
    Validator::make(
        ['upload' => $value],
        ['upload' => 'required|mimes:txt,csv'],
    )->validate();
}

public function updatedUpload()
{
    $this->columns = Csv::from($this->upload)->columns();
    $this->guessWhichColumnsMapToWhichFields();
}

public function import()
{
    // Validate that you are importing any data
    $this->validate();

    $importCount = 0;
    Csv::from($this->upload)
    ->eachRow( function ($row) use (&$importCount){
        $eachRow = $this->extractFieldsFromRow($row);

        //Validate the data of each Row to make to make sure you don't import duplicate records   
        $this->validateOnly(collect($eachRow), [
            'fieldColumnMap.first_name' => 'required|max:255',
            'fieldColumnMap.last_name' => 'required|max:255',
            'fieldColumnMap.email' => 'required|max:255|email|unique:account_users, email',
            'fieldColumnMap.extension' => 'required|numeric|unique:account_users, extension',
            'fieldColumnMap.password' => 'required|max:255',
            'fieldColumnMap.user_type' => 'required|in:user,admin',
        ]);

        //If validation fails, it should skip the create extension part and run the next row

        //If validation pass, then create the Extension
        AccountUser::create([
            'user_id' => Auth::user()->id,
            'account_id' => $this->clientID,
            'first_name' => $eachRow['first_name'],
            'last_name' => $eachRow['last_name'],
            'email' => $eachRow['email'],
            'password' => $eachRow['password'],
            'extension' => $eachRow['extension'],
            'user_type' => $eachRow['user_type'],
        ]);
        $importCount++;
    });
    $this->reset();
    $this->emit('refreshExtensions');
    $this->notify('Successfully Imported '.$importCount.' Extensions');
}

另外,如果验证失败,我该怎么做才能转到下一行而不是尝试创建扩展。

谢谢。

【问题讨论】:

  • 这并不能直接回答您的问题,但是您为什么不通过 collect($rowsOrStmt) 将 CSV 的所有行放入一个集合中,然后使用 ->reject 并运行一个简单的 laravel那个闭包中的验证器?剩下的你可以添加->each 来完成你的模型工作......我的意思是你似乎不需要验证消息。
  • 感谢您的想法。但那会是什么样子呢?我尝试过的任何东西都使用来自protected $rules 的规则,但这些不是我对 CSV 的每个字段都需要的规则。我想我能做的是,如果任何一行失败,就会抛出一个错误。但同样,验证是不起作用的部分。

标签: php laravel laravel-livewire


【解决方案1】:

我能够为此创建自定义规则。如果一行验证失败,我只会抛出一个错误。所以,基本上要么所有行都通过,要么全部失败。 这是它现在的样子:

public function import()
{
    // Validate that you are importing any data
    $this->validate();

    $importCount = 0;
    Csv::from($this->upload)
    ->eachRow( function ($row) use (&$importCount){
        $eachRow = $this->extractFieldsFromRow($row);

        $validatedData = Validator::make([
            'first_name' => $eachRow['first_name'],
            'last_name' => $eachRow['last_name'],
            'email' => $eachRow['email'],
            'password' => $eachRow['password'],
            'extension' => $eachRow['extension'],
            'user_type' => $eachRow['user_type'],
            ],[
            'first_name' => 'required',
            'last_name' => 'required',
            'email' => 'required|email|unique:account_users',
            'extension' => 'required|numeric|unique:account_users',
            'password' => 'required|max:255',
            'user_type' => 'required|in:user,admin',
        ],);

        if($validatedData->fails()){
            $this->notify(['error','Oops something went wrong!']);
        }else{
            AccountUser::create([
                'user_id' => Auth::user()->id,
                'account_id' => $this->clientID,
                'first_name' => $eachRow['first_name'],
                'last_name' => $eachRow['last_name'],
                'email' => $eachRow['email'],
                'password' => $eachRow['password'],
                'extension' => $eachRow['extension'],
                'user_type' => $eachRow['user_type'],
            ]);
            $importCount++;
        }
    });

    $this->reset();
    $this->emit('refreshExtensions');
    if($importCount!=0) $this->notify(['success','Successfully Imported '.$importCount.' Extensions']);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 2017-01-27
    • 2016-06-15
    • 2016-11-28
    • 1970-01-01
    • 2016-09-28
    相关资源
    最近更新 更多