To achieve the conditional validation for the pay_date field based on the $status variable, you can use Laravel's Validator class with a custom rule. Here's how you can implement this:
use Illuminate\Support\Facades\Validator;
function validateInvoiceForm($data, $status)
{
$rules = [
'pay_date' => [
function ($attribute, $value, $fail) use ($status) {
if ($status === 'attested') {
// If status is 'attested', pay_date can be empty or a valid date
if (!empty($value) && !strtotime($value)) {
$fail('The ' . $attribute . ' must be a valid date.');
}
} else {
// If status is not 'attested', pay_date must be empty
if (!empty($value)) {
$fail('The ' . $attribute . ' must be empty.');
}
}
},
],
];
$validator = Validator::make($data, $rules);
if ($validator->fails()) {
return $validator->errors();
}
return 'Validation passed!';
}
// Example usage
$data = ['pay_date' => '2023-10-15'];
$status = 'attested';
$result = validateInvoiceForm($data, $status);
echo $result; // Outputs: Validation passed!
Explanation:
-
Custom Validation Rule: We define a custom validation rule using a closure. This allows us to apply logic based on the
$statusvariable. -
Condition for 'attested' Status: If
$statusis'attested', thepay_datecan be either empty or a valid date. We check if thepay_dateis not empty and is a valid date usingstrtotime. -
Condition for Other Statuses: If
$statusis not'attested', thepay_datemust be empty. We check if thepay_dateis not empty and fail the validation if it is. -
Validation Execution: We use Laravel's
Validator::maketo apply the rules to the data. If validation fails, we return the errors; otherwise, we return a success message.
This approach allows you to dynamically apply validation rules based on the $status variable.