Search code examples
laravelmaatwebsite-excel

How can i duplicate validation in laravel when i input data by csv using maatwebsite


Here is the insert into database code I use the database field sreg_no unique. SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1312764483' for key 'administrations_sreg_no_unique'

    public function storestudent(Request $request){
        $request->validate([
            'file' =>'required|file|mimes:csv,txt|max:2048',
        ]);
        if ($request->hasFile('file')) {
            $path=$request->file('file')->getRealPath();
            $data=Excel::load($path)->get();
            foreach ($data as  $row) {


                Administration::create([
                    'sname'=>$row->sname,
                    'sfname'=>$row->sfname,
                    'smname'=>$row->smname,
                    'student_mobile'=>$row->student_mobile,
                    'admission_roll'=>$row->admission_roll,
                    'sboard_name'=>$row->sboard_name,
                    'spass_year'=>$row->spass_year,
                    'sroll_no'=>$row->sroll_no,
                    'sreg_no'=>$row->sreg_no,
                    'sgroup'=>$row->sgroup,
                    'sgpa'=>$row->sgpa,
                    'hboard_name'=>$row->hboard_name,
                    'hpass_year'=>$row->hpass_year,
                    'hroll_no'=>$row->hroll_no,
                    'hreg_no'=>$row->hreg_no,
                    'hgroup'=>$row->hgroup,
                    'hgpa'=>$row->hgpa,
                    'm_position'=>$row->m_position,
                    'session'=>$row->session,
                    'faculty'=>$row->faculty,
                    'student_password'=>$row->student_password,
                    'gender'=>$row->gender
                ]);

                //Notify Student

            }
        }
        session()->flash('success', 'Student Inserted  Successfully !!');
        return redirect()->back();
    }

Actually i want to get notify to user who input data. this is duplicate data . Thanks


Solution

  • Check if the data contains a duplicate number before attempting to create the new Administration record:

    if (Administration::where('sreg_no', $row->sreg_no)->exists()) {
        session()->flash('error', 'Duplicate Student Registration Number');
        return redirect()->back();
    } else {
        // create new administration record, notify the student, and return redirect back
    }