【问题标题】:Laravel maatwebsite Import Error and Exception handlingLaravel maatwebsite 导入错误和异常处理
【发布时间】:2020-11-24 10:16:08
【问题描述】:

我正在尝试使用 maatwebsite 来在我的系统中导入 excel 文件,我正在使用带有队列的 Collection 来执行导入,因为我与另一个表有关系,导入正在工作,但如果它们我无法得到错误发生这是我的导入模型代码

<?php
namespace App\Models;

use Maatwebsite\Excel\Concerns\RegistersEventListeners;

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Events\BeforeSheet;
use Modules\UserCategory\Entities\UserCategory;
use Maatwebsite\Excel\Concerns\ToCollection;

use Illuminate\Support\Facades\Validator;

use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithValidation;

use Maatwebsite\Excel\Concerns\WithChunkReading;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Notifications\ImportHasFailedNotification;

use Hash;
use Log;
use Mail;
use Session;
class Import_Users implements ToCollection, WithHeadingRow, WithEvents,WithValidation,WithChunkReading,ShouldQueue
{
    use RegistersEventListeners,Importable;
public function rules(): array
    {
        return [
         '*.email'=>['email','unique:users,email']

        ];
    }



    public function collection(Collection $rows)
    {
        Validator::make($rows->toArray(), [
            '*.namess' => 'required',
            '*.email'=>['email','unique:users,email'],
        ])->validate();

        foreach ($rows as $row)
        {     $this->validationFields($row);
            $password = rand(11111111, 99999999);
            $pass=Hash::make($password);
            $time = strtotime($row['date_of_birth']);
           $newformat = date('Y-m-d', $time);
            if(isset($row['user_categories']))
                $Cates=$row['user_categories'];
            else
                $Cates='';
            $array = explode(',', $Cates);
            $cateable_array=$this->Handlecategory($array);


            $nums = [];
            $selected=false;
            $correct_order = [];
            $maping = array();
            $this->count = count($row);
            $count = count($row);
            $map_array = array();
            $questions = [];
            $sheet=$this->sheet_name;

            $this->set_role(  $sheet );

                $user = User::create([


                    'name' => $row['name'],
                    'first_name' => $row['first_name'],
                    'last_name' => $row['last_name'],
                    'email' => $row['email'],
                    'gender' => $row['gender'],
                    'date_of_birth' => $newformat,

                    'password' => $pass,
                    'password_confirmation' => 1,


                ]);

                $user->userCategory()->attach($cateable_array);
                $user->syncRoles($this->role);



            if ($this->session_toggle==='true') {
            $this->SendEmailusers($user,$password);

           }
        }
    }

我正在使用验证,但验证似乎不起作用并且没有给我任何错误。 这就是我在控制器中调用导入类的方式

 public function import_xlsx(Request $request)
    {
        $i = 0;
        $j = 0;
        $module_title = $this->module_title;
        $module_name = $this->module_name;
        $module_path = $this->module_path;
        $module_icon = $this->module_icon;
        $module_model = $this->module_model;
        $module_action = 'import Excel';
        $module_name_singular = Str::singular($module_name);
        $import_file = Session::get('Excel_file_users');
        $send_mail_toggle = Session::get('Import_user_send_email');

        $data = [];
        $import = new Import_Users();
        $msg = 'Users Added To the Queue ,will inform You when it finish ';
        // $import_file= '/upload/Import/sheet.xls';
        Log::info('session from controller' . $send_mail_toggle);

 try {
     $result = Excel::import($import, storage_path($import_file))->chain([

         new NotifyUserImportComplete(request()->user()),
     ]);

 }
 catch (\Exception $e){
     Log::info('exception');

 }
 catch ( ValidationException $e ){

  Log::info("fffffffffffffffffffffffffffffff");
 }
        Flash::success("<i class='fas fa-check'></i> " .$msg)->important();


        return redirect("admin/$module_name");
    }

【问题讨论】:

    标签: php excel laravel maatwebsite-excel


    【解决方案1】:

    您应该记录错误和/或在会话中将其闪烁,就像您发送成功消息一样

    catch (\Exception $e){
        Log::error($e->getMessage());
        return back("admin/$module_name")->withErrors($e->getMessage());
    }
    

    【讨论】:

    • 谢谢您的回复,实际上它必须工作但什么都没有发生,我正在使用队列,正如我所说,队列无法捕获异常?
    • 您的队列在运行吗?你看过工作表吗? NotifyUserImportComplete 队列中有什么?
    • 是的,它正在工作,但没有插入数据,因为我试图插入不是唯一的电子邮件,所以它应该抛出异常或给我错误,但它确实,没有任何事情,另一方面,如果我是尝试插入唯一的电子邮件,它插入没有问题
    • @NetcomAsk 作业表用于您的队列的成功操作和 failed_jobs 表用于检查您从队列中获得的错误。
    • 是的,我在失败的作业表中有一条记录,但我该如何处理它以及为什么它会在那里引发验证错误?
    猜你喜欢
    • 1970-01-01
    • 2014-04-06
    • 2012-09-15
    • 1970-01-01
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-16
    相关资源
    最近更新 更多