How to validate each value in an array Laravel?

Laravel provides many different approaches to validate an application’s incoming data. To validate an array, we have different rules of validation that we can apply to validate each value in an array. For example, to ensures that each value of the input is an array. A list can be provided as context to the validation rule to tell Laravel to ensure that the keys are present in the input.

public function rules()
    {
        return [
            'post' => 'array:title', // title must be present in input
        ];
    }

The above rule is applied on the posts array. This returns true if each title in the array is present and not empty.

Validating array from input fields may require to validate that each value in a given array input field is unique, you can use the Validator class and do the following for this check.

validator = Validator::make($request->all(), [
    'person.*.email' => 'email|unique:users',
    'person.*.first_name' => 'required_with:person.*.last_name',
]);

The rule above checks if every person in the array has a unique email. You can use the * character to specify custom validation messages, as shown below.

'custom' => [
    'person.*.email' => [
        'unique' => 'Every person should have a unique e-mail address',
    ]
]

Similarly, we can apply other rules to an array. We can apply all validation rules as we do with single inputs to validate each value in an array. For example the distinct rule can be used on an array as shown below.

public function rules()
    {
        return [
            'post.*.id' => 'distinct', 
        ];
    }

This returns true if all posts in an array have distinct ids.

We can use the exclude validation rules for an array. Each rule compares the current field with another field and excludes it from the returned data based on the specific condition. exclude_if excludes the current field if another field is equal to any value. exclude_unless excludes the current field unless another field is equal to any value. exclude_without excludes the current field if another field is not present.

public function rules()
    {
        return [
            'meta_title' => 'exclude_if:title,"digital"|required|array', // 
            'title' => 'exclude_unless:meta_title,null|required|array',
            'meta_desc' => 'exclude_without:meta_title|sometimes|array'
        ];
    }

Leave a Comment