Consider this validation:
Route::post('/validate', function (Request $request): JsonResponse {
$validated = $request->validate([
"insurance_plan" => ["required", "in:Commerical Insurance,Government,Uninsured"],
"insurance_hasSecondaryPrescriptionInsurance" => ["boolean"],
'insurance_secondaryPrescriptionName' => ['required_if:insurance_hasSecondaryPrescriptionInsurance,true', 'required_if:insurance_plan,Government,Commericial Insurance' ]
]);
return response()->json([
'validated' => $validated
]);
});
For insurance_secondaryPrescriptionName
, I’m looking to do a AND validation. If insurance_plan has those value ‘Uninsured’ AND insurance_hasSecondaryPrescriptionInsurance is true.
So if I send out this request it should pass validation:
POST https://localhost/api/validate
Content-Type: application/json
Accept: application/json
{
"insurance_plan": "Uninsured",
"insurance_hasSecondaryPrescriptionInsurance": true,
"insurance_secondaryPrescriptionName": ""
}
Does this require a custom validator or is there a preexisting validation I can use?
2
Answers
I was able to figure this out by extending Validator (based off of this How to use multi required_if in laravel?).
And I could use it in my code like so:
To use an "AND" logic or to add more complex validation logics you need to use
Rule::requiredIf()
to create a custom rule validator using a closure (https://laravel.com/docs/10.x/validation#rule-required-if):