My Solution for Validation in Update Request for Unique Data in Laravel Controller

بِسْمِ اللّهِ الرَّحْمَنِ الرَّحِيْمِ
اللهم صل على محمد وآل محمد
السَّلاَمُ عَلَيْكُمْ وَرَحْمَةُ اللهِ وَبَرَكَاتُه


I have been searching for the solution to validate the data when we try to update the form and still want to keep the data in unique. After done some research on the documents and other possible solution. This works the best for me, may it helps u too.

for my case, I have to make sure the Student MRN is still unique while updating, so I need to add 

unique:students,student_mrn,{$student>id}"'

format - unique:tableName, tableRowThatNeedsToBeUnique, {$tableName>tablePrimaryKey} 

This is to make sure the data that has to be checked on the back end should just compare with the current table & current ID not the whole table yet. and also, dont forget to use " not ' . It gives such an impact btw :')


public function update(Request $request, Student $student)
    {
        $request->validate([
            'student_name' => 'required',
            'student_age' => 'required|integer|min:1|max:200',
            'student_gender' => 'required',
            'student_class' => 'required',
            'student_mrn' => "required|min:9|max:12|unique:students,student_mrn,{$student->id}",
            //Minimum 9: Passport number
            //Maximum 12: IC number
            'teacher_name' => 'required',
            ]);

        $student->update([
            'student_name' => $request->input('student_name'),
            'student_age' => $request->input('student_age'),
            'student_gender' => $request->input('student_gender'),
            'student_class' => $request->input('student_class'),
            'student_mrn' => $request->input('student_mrn'),
            'teacher_name' => $request->input('teacher_name'),
        ]);

        return redirect('student/')
            ->with('message',"Student name: $student->student_name edited successfully!");
        
    }

Jangan Lupa Follow Saya Di Platform Lain. Moga bermanfaat. 
👉 Join Telegram Channel : https://t.me/mohdnoorshawal 

اللهم صل على محمد وآل محمد
(Allahumma salli 'ala Muhammad wa ali Muhammad)
سُبْحَانَ اللّهِ وَ بِحَمْدِهِ ، سُبْحَانَ اللّهِ الْعَظِيمِ
(SubhanAllahi wa biHamdihi, SubhanAllahil adzim)
سبحانك اللهم وبحمدك أشهد ان لا إله إلا أنت أستغفرك وآتوب إليك
(Subhanakallahumma wabihamdika asyhadu allaailaaha illa anta astaghfiruka wa atuubu ilaika)

Post a Comment

2 Comments

Emoji
(y)
:)
:(
hihi
:-)
:D
=D
:-d
;(
;-(
@-)
:P
:o
:>)
(o)
:p
(p)
:-s
(m)
8-)
:-t
:-b
b-(
:-#
=p~
x-)
(k)