0

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 Answer 1

0

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',
]);
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you. But I don't have access to the $request in my class .. in code. Validating is in a class that extends of FormRequest class.. something like this tutorial itsolutionstuff.com/post/…
hello pedram shabani, this is a unique validation public function rules() { return [ 'name' => 'required|max:10', 'slug' => $this->getSlugRules(), ]; }
dear Kishan, I don't know what you mean!!!
Hi dear pedram , the part I did not understand is that the variable types of your rules . Are id , key and value all array ? I mean id is an array , key is an array and so on ..
if it is possible dd your request() and add it to your question .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.