简体   繁体   English

验证后挂钩未重定向到表单页面

[英]After Validation Hook not redirecting to the form page

I'm building a small validator for my form with laravel 7 and i needed a custom logic to be added after the standard validation so I used the after validation hook as in doc .我正在使用 laravel 7 为我的表单构建一个小型验证器,我需要在标准验证之后添加一个自定义逻辑,因此我使用了doc中的 after validation hook。 My issue is not with the logic of the controller but the fact that after the validation occur and I add the custom error message i don't get redirected to the original form.我的问题不在于 controller 的逻辑,而是在验证发生之后我添加了自定义错误消息,我没有被重定向到原始表单。 What I'm missing?我错过了什么?

public function store(Request $request)
    {
        //
        $data = $request->all();
        $newSpn = new Sponsorization;
        $userId = Auth::id();
        $paymentPlanId = $data["payment_plan_id"];
        $apartmentId = $data["apartment_id"];
        $payPlanInfo = PaymentPlan::find($paymentPlanId)->hours_duration;
        $alreadyActive = $this->alreadyActive($apartmentId);

        $userApartment = DB::table('apartments')
                            ->where('user_id', $userId)
                            ->pluck('id');

        $validator = Validator::make($request->all(),[
            'payment_plan_id' => "required",
            'appartment_id' => [
                'required',
                Rule::in($userApartment)
            ]
        ]);

        $validator->after(function ($validator) use ($alreadyActive){
            if ($alreadyActive) {
                $validator->errors()->add('apartment_promo', 'A promo is already active on this apartment!');
        }
    });


    if ($validator->fails()) {
        //
    }

    $newSpn->apartment_id = $apartmentId;
    $newSpn->payment_plan_id = $paymentPlanId;
    $newSpn->start_date = date("Y-m-d H:m:s");
    $newSpn->end_date = date("Y-m-d H:m:s",strtotime("+{$payPlanInfo} hours"));

    $newSpn->save();
} 

You can redirect back to the page where you come from like this您可以像这样重定向回您来自的页面

if ($validator->fails()) {
    return redirect()->route('name.of.route.where.you.come.from')
        ->withErrors($validator)
        ->withInput();
}

As you want to be redirect to the orignal form you must define that behaviour when the validation failed so you can pass the validation errors and old input values calling the method withErrors and withInput当您希望重定向到原始表单时,您必须在验证失败时定义该行为,以便您可以传递验证错误和调用方法withErrorswithInput的旧输入值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM