0

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(), 
    ]));
}
1
  • try passing the all request data into those class $amexData = new StoreAmexRequest( $request->all() ) Commented Feb 18, 2023 at 4:00

1 Answer 1

3

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
    ];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.