Search code examples
laravellaravel-validation

Validation of array in laravel


I am building a small application in Laravel 5.6 where I am having an api which takes an array in format [1,2,5,90,25] I want to validate as required field in my validation rule.

I tried creating a request and validating the same as:

public function rules()
{
    return [
        'ProjectType.*'=>  'required',
    ]
}

public function messages()
{
    return [
        'projectType.*.required' => 'Project type is required',
    ];
}

But this thing is not working out, even if an empty array [] is being passed it accepts it.

How can we achieve these kind of array format


Solution

  • You must validate at the top level of the array, you may want this validation:

    public function rules()
    {
        return [
            'ProjectType'=>  'required|array',
            'ProjectType.*'=>  'required',
        ]
    }
    
    public function messages()
    {
        return [
            'projectType.*.required' => 'Project type is required',
        ];
    }