Laravel Validating An Array in Update Method unique filter

111 views Asked by At

I am new to Laravel. I try to validate an array in Laravel 9. for using a unique filter I have a problem. at first, I try to use this way

$rules =  [
    '*.id' => 'integer|required',
    '*.key' => 'string|unique.settings|max:255|required',
    '*.value' => 'array|nullable|max:255',
];

For the Create method, this works, but for updating, the logic is wrong. I need to ignore the current field.

for the update, I try to use this way

private function update(): array
{
    foreach ($this->request->all() as $keys => $values) {
        // dd($values['id']);
        $rules[$keys .'.id' ] = 'integer|required';
        $rules[$keys .'.key'] = ['string|max:255|required', Rule::unique('settings', 'key')->ignore($values['id'])];
        $rules[$keys .'.value'] = 'array|nullable|max:255';
    }
    //  dd($rules);
    return $rules;
}

I got this error

BadMethodCallException: Method Illuminate\Validation\Validator::validateString|max does not exist. in file /Users/mortezashabani/code/accounting/vendor/laravel/framework/src/Illuminate/Validation/Validator.php on line 1534

how can I validate an array in the update method in Laravel 9?

PS: without Rule::unique('settings','key')->ignore($values['id'])] all filter is works without any problem

1

There are 1 answers

5
kishan jethava On

hello you can try this code in your function

$validated = $request->validate([
    'id' => 'required',
    'key' => 'string|unique.settings|max:255|required',
    'value' => 'array|nullable|max:255',
]);