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

#ActionPills | Shawal 🇵🇸
2 min readNov 5, 2022

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}”,

--

--

#ActionPills | Shawal 🇵🇸
#ActionPills | Shawal 🇵🇸

Written by #ActionPills | Shawal 🇵🇸

Sharing weekly #ActionPills for both of you and ME. Let's consume and apply this 'actionable pills' in our daily life ^^ > https://taplink.cc/actionpills <

No responses yet