I am validating a credit card, for which I created two form requests:
php artisan make:request StoreAmexRequest
php artisan make:request StoreVisaRequest
How can I use them in the same controller?
public function store(Request $request)
{
if ($request->credit_card['number'][0] == 3) {
new StoreAmexRequest(),
}
if ($request->credit_card['number'][0] == 4) {
new StoreVisaRequest(),
]);
}}
My code doesn't work, the $request variable doesn't receive the StoreAmexRequest()
.
I am creating a credit card validator, the AMEX card validator is different from VISA cards, since AMEX is 15 digits and the CVV is 4 digits, and in VISA it is 16 digits.
It is necessary to use php artisan make:request since it is for an API that returns the response in JSON?
\app\Http\Requests\StoreAmexRequest
:
public function authorize()
{
return true;
}
public function rules()
{
$year = date('Y');
return [
'credit_card.name' => ['required', 'min:3'],
'credit_card.number' => ['bail', 'required', 'min:15', 'max:16', new CredirCardRule],
'credit_card.expiration_month' => ['required', 'digits:2'],
'credit_card.expiration_year' => ['required', 'integer', 'digits:4', "min:$year"],
'credit_card.cvv' => ['required', 'integer', 'digits_between:3,4']
];
}
public function failedValidation(Validator $validator)
{
throw new HttpResponseException(response()->json([
$validator->errors(),
]));
}
You could just use a single form request that validates both.
public function store(StoreCreditCardRequest $request)
{
YourCreditCardModel::create($request->validated());
}
And split the rules inside the form request
public function rules(): array
{
if ( $this->credit_card['number'][0] == 3 ) {
return $this->amexRules();
}
if ( $this->credit_card['number'][0] == 4 ) {
return $this->visaRules();
}
}
protected function amexRules(): array
{
return [
// your validation rules for amex cards
];
}
protected function visaRules(): array
{
return [
// your validation rules for visa cards
];
}