How to validate an array of dates in laravel?

by muriel.schmidt , in category: PHP Frameworks , 5 months ago

How to validate an array of dates in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elisha_langworth , 5 months ago

@muriel.schmidt 

In Laravel, you can validate an array of dates using the array validation rule combined with the date validation rule. Here's an example of how you can validate an array of dates in a request class:

1
2
3
4
5
6
7
public function rules()
{
    return [
        'dates' => 'required|array',
        'dates.*' => 'required|date',
    ];
}


In this example, we are validating that the dates input field is an array and that each element inside the array is a valid date format. The dates.* rule applies the validation rules to each element in the array.


You can use this validation in your controller to validate the request data before processing it, like this:

1
2
3
4
5
6
7
8
9
public function store(Request $request)
{
    $validatedData = $request->validate([
        'dates' => 'required|array',
        'dates.*' => 'required|date',
    ]);

    // Further processing of the validated data
}


If any of the dates in the array fail the validation rules, Laravel will automatically return an error response with the validation messages.