首页 > 解决方案 > 导入 CSV 文件时的每行验证

问题描述

我正在将 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');
}

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

谢谢。

标签: phplaravellaravel-livewire

解决方案


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

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

推荐阅读