如何在laravel中验证同一控制器中的2个表单请求

li9yvcax  于 2023-02-20  发布在  其他
关注(0)|答案(1)|浏览(129)

我正在验证信用卡,为此创建了两个表单请求:
php工匠制造:请求StoreAmexRequest php工匠制造:请求StoreVisaRequest
如何在同一个控制器中使用它们?

public function store(Request $request)
{  

    if ($request->credit_card['number'][0] == 3) {

       new StoreAmexRequest(),

    }
    if ($request->credit_card['number'][0] == 4) {

       new StoreVisaRequest(),

        ]);

    }}

我的代码不起作用,$request变量不接收它StoreAmexRequest()
我正在做一个信用卡验证器,美国运通卡验证器是不同于VISA卡,因为美国运通是15位数和CVV是4位数,在VISA是16位数。
有必要使用php artisan make:request,因为它是用于以JSON格式返回响应的API
\app\Http\请求\美国运通商店请求

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(), 
    ]));
}
9avjhtql

9avjhtql1#

您可以只使用一个表单请求来验证两者。

public function store(StoreCreditCardRequest $request)
{
    YourCreditCardModel::create($request->validated());
}

并拆分表单请求中的规则

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
    ];
}

相关问题