layout( 'components.admin-layout' ); } public function importStudents() { $this->resetErrorBag(); // 在這裡處理學生資料的匯入邏輯 //am071001`A!3$$E%91`aaaa@gmail.com`王小明 //school_no,password,email,name if ( empty( $this->students ) ) { $this->addError( 'students', '請輸入學生資料' ); return; } $formData = explode( "\n", $this->students ); try { $students = array_map( function ($student) { $studentData = explode( '`', $student ); return [ 'school_no' => strtolower( trim( $studentData[0] ) ), 'password' => trim( $studentData[1] ), 'email' => trim( $studentData[2] ), 'name' => trim( $studentData[3] ), 'valid_date' => trim( $studentData[4] ), ]; }, $formData ); } catch (\Exception $e) { $this->addError( 'students', '學生資料格式錯誤,請檢查是否有空白或缺少資料' ); return; } // validate $validatedData = collect( $students )->map( function ($student) { return validator( $student, [ 'school_no' => 'required|string|max:255|regex:/^[A-Za-z]{2}\d{6}$/', 'password' => 'required|string|max:50', 'email' => 'required|email|max:255', 'name' => 'required|string|max:255', 'valid_date' => 'required|date', ] )->validate(); } ); // dd($validatedData); // 檢查學號是否曾經匯入過 if ( $this->is_overwirte_data !== true ) { // get school_no prefix, for example: am071001 => am071 $schoolNoPrefix = substr( $validatedData[0]['school_no'], 0, 5 ); if ( User::where( 'school_no', 'like', $schoolNoPrefix . '%' )->exists() ) { // 學號已存在 $this->addError( 'students', "學號開頭 {$schoolNoPrefix} 的資料曾經匯入過,若要更新請勾選覆蓋資料" ); return; } } try { DB::transaction( function () use ($validatedData) { //使用交易 foreach ( $validatedData as $student ) { // 新增或更新學生資料 User::updateOrCreate( [ 'school_no' => $student['school_no'] ], $student ); // dd($student); // 模擬錯誤(這裡會導致回滾) //throw new Exception("Something went wrong!"); } } ); } catch (Exception $e) { $this->addError( 'students', '匯入學生資料失敗,請檢查資料格式是否正確或聯絡全端工程師' ); // dd($e); return; } // 清空輸入框 $this->students = ''; // 提示匯入成功 session()->flash( 'message', '匯入學生資料成功' ); } }