Laravel:csv 验证

Laravel: csv validations

我如何在上传前验证 csv 文件中的字段。

我想在上传之前从 csv 文件中获取所有重复的电子邮件 ID,这些 ID 已经在 db 中可用。

如果文件中有重复项,则上传除重复项以外的其他文件,并在上传后显示所有重复的电子邮件 ID

    public function store(Request $request)
{
    $upload = $request->file('upload-file');
    $getPath = $upload->getRealPath();

    $file = fopen($getPath,'r');        

    while($columns = fgetcsv($file))
    {
        if($columns[0]=="")
        continue;


        $data =  $columns;


        foreach($data as $key=>$value)
        {
            $name = $data[0];
            $email = $data[1];
            $password = $data[2];

        }

        try{
            $user = User::Create(
                [
                    'name'=>$name,
                    'email'=>$email,
                    'password'=>$password,
                ]);
            $user->save();
        }
        catch(Exception $e)
        {
          if($e->getCode() == 23000)
              return 'we have found duplicate records';
          else
              $e->getCode();
        };

    }

你可以做的是,创建任何私有数组变量,public 等(任何你想要的)并将所有 excel 值推送到该变量并使用该数组找到唯一的结果集php 函数并将它们存储到数据库中。

public $records = [];
public function store(Request $request)
{
    $upload = $request->file('upload-file');
    $getPath = $upload->getRealPath();

    $file = fopen($getPath,'r');        

    while($columns = fgetcsv($file))
    {
        if($columns[0]=="")
        continue;


        $data =  $columns;
        array_push($this->records, data);



    }
}

array_unique($this->records)//it will give you unique results set and insert bulk insert

所以你可以这样做。

      public function store(Request $request)
    {
        $upload = $request->file('upload-file');
        $getPath = $upload->getRealPath();

        $file = fopen($getPath,'r');        

        while($columns = fgetcsv($file))
        {
            if($columns[0]=="")
            continue;


            $data =  $columns;


            foreach($data as $key=>$value)
            {
                $name = $data[0];
                $email = $data[1];
                $password = $data[2];

            }

            try{
             if (!User::whereEmail($email)->exists()) {
                $user = User::Create(
                    [
                        'name'=>$name,
                        'email'=>$email,
                        'password'=>$password,
                    ]);
                $user->save();
             }
            }
            catch(Exception $e)
            {
              if($e->getCode() == 23000)
                  return 'we have found duplicate records';
              else
                  $e->getCode();
            };

        }