Reputation: 635
I am trying to update the data and to do this I am using a method patch on my form.
Update Validation Request
use Illuminate\Validation\Rule;
'question' => [
'required',
'string',
Rule::unique('faqs_questions','question'),
'max:30',
],
If there are no changes in my question it gives me an error:
The question has already been taken.
dd($this->toArray())
on validation request gets me below output:
array:9 [▼
"_method" => "PATCH"
"_token" => "LLqlQfMpzSdyAInVOaqs5lqBMbEvNT9eMDU9ZZxJ"
"my_name_TOApMPqqwwBasdts9bLa" => null
"valid_from" => "eyJpdiI6IkJ2TUpZV29ZV0Qzasdasdaasgst5345wtgrtyegq4yhq4qhgqgMDU1"
"question" => "Question B"
"answer" => "Answer B"
]
I tried using Rule::unique('faqs_questions','question')->ignore($this->question),
on my request file but I think it needs id which we don't have in any inputs. Is there any way to resolve it?
Upvotes: 0
Views: 5629
Reputation: 437
Here is my working example of the validation in laravel 8,
public function edit($id, Request $request){
$request->validate([
'email' => 'required|email',Rule::unique('users')->ignore($id, 'id'),
'fname' => 'required',
'sname' => 'required',
'lname' => 'required',
]);
$user = User::find($id);
$input = $request->all();
$results = array_filter($input);
$user->fill($results)->save();
return response()->json(['user' => $user, 'success' => 'Your Info Has been Saved']);
}
If I understood your question well
Upvotes: 1
Reputation: 10210
You could do the following which uses a where
clause to say we want to check the question
is not already in the table.
$validator = Validator::make(['question' => $request->question], [
'question' => [
'required',
'string',
Rule::unique('faq_questions')->where('question', '!=', $request->question),
'max:30'
]
]);
You can change the field it checks against to be whatever you want, hopefully the above gives you the general idea.
Then you can check if validation was successful or unsuccessful:
if ($validator->fails()) {
// error
}
Upvotes: 1
Reputation: 5715
What about putting it into a hidden input?
If whatever you're sending via question
is unique, you can also use something like this: Rule::unique('users')->ignore($this->question, 'slug')
Upvotes: 0