Search code examples
phplaravel

Is there a way to validate array keys?


I have checkboxes with name category[{{$category->id}}]. I'd like to validate the category id for these checkboxes whether it is a valida id or something else. I found that arrays can be validated this way:

    $input = $request->validate([
        'category' => 'nullable|array',
        'category.*' => 'integer|min:1',
        'keywords' => 'nullable|string|min:1|max:2000'
    ]);

The problem that I want to validate the keys, not the values. Is there a way to do so with Laravel validation rules?

For example the input is something like {"category": {"1": "on", "8": "on", ...}} in JSON format and I want to check whether 1 and 8 are category ids or at least they are integers. Not sure if the validator is capable of doing this. If not, then I'll send a feature request for it.


Solution

  • To validate the checkboxes with names like category[{{$category->id}}] in Laravel, where each checkbox name is tied to a specific category-ID , you can use the exists rule to ensure that the category-ID exists in the database.

    Do this. I think it will resolve your issue...

    $input = $request->validate([
        'category' => 'nullable|array',
        'category.*' => 'integer|exists:categories,id' //assumed `categories` is respected table in DB
    ]);
    

    For detailed information you can check the Specifying a Custom Column Name section of the official-docs.

    As of validating the keys, you need to prepare the request. The best way is moving the whole thing into a FormRequest and use the prepareForValidation method.

    class ProductSearchRequest extends FormRequest
    {
        public function authorize(): bool
        {
            return true;
        }
    
        protected function prepareForValidation(): void {
            $this->merge([
                'category' => isset($this->category)?array_keys($this->category):[],
                'keywords' => isset($this->keywords)?str_replace('%', '', $this->keywords):''
            ]);
        }
    
        public function rules(): array
        {
            return [
                'category' => 'nullable|array',
                'category.*' => 'integer|min:1|exists:categories,id',
                'keywords' => 'nullable|string|min:0|max:2000'
            ];
        }
    }