'how to ignore array ID for validating array in Laravel?
That I want to make validation on an array value, and this is my code:
I have a function that can make a query to another table using hasMany but I want to validate that query must be unique. I tried to use this "required|unique:deed_legalization_numbers, number" and that's work but when I tried to update/edit some field, it will return already taken.
Then i tried to make ignoring ID in unique:
"required|unique:deed_legalization_numbers, number, [$request->input('deed_legalization_numbers')]"
it will return array to string conversion, because not support array
Then I tried this code:
$deed_legalization_numbers = $request->input('deed_legalization_numbers.*.number');
$deed_legalization_id = $request->input('deed_legalization_numbers.*.id');
$rules = [
'deed_legalization_numbers.*.number' => //'required|unique:deed_legalization_numbers,number,deed_legalization_numbers.*.id',
[
'required',
Rule::unique('deed_legalization_numbers')->where(function ($query) use ($deed_legalization_numbers, $deed_legalization_id) {
return $query->whereIn('number', $deed_legalization_numbers);
})->ignore($deed_legalization_id[0]) // The problem in this line
],
];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput();
}
I want to ignore that deed_legalization_numbers ID from checking, if i changed variable $deed_legalization_id[0] to $deed_legalization_id
it will return error :
Status Code: 500 Internal Server Error
Symfony\Component\Debug\Exception\FatalErrorException: Method Illuminate\Validation\Rules\Unique::__toString() must not throw an exception, caught ErrorException: addslashes() expects parameter 1 to be string, array given in file ..path\vendor\laravel\framework\src\Illuminate\Validation\ValidationRuleParser.php on line 233
0 {main}
Solution 1:[1]
Your self-answer was helpful. Not sure if it was there 2 years ago, but there is an undocumented helper method called whereNotIn() that allows you to skip the callback stuff. So I would do this for your case:
$deed_legalization_id = $request->input('deed_legalization_numbers.*.id');
$rules = [
'deed_legalization_numbers.*.number' => [
'required',
'distinct',
Rule::unique('deed_legalization_numbers', 'number')
->whereNotIn('id', $deed_legalization_id),
],
];
This results in the same database query:
select count(*) as aggregate from `deed_legalization_numbers` where `number` = ? and (`id` not in (?));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | miken32 |
