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

After Validation Hook not redirecting to the form page

我正在使用 laravel 7 为我的表单构建一个小型验证器,我需要在标准验证之后添加自定义逻辑,所以我使用了 doc 中的验证后挂钩。我的问题不在于控制器的逻辑,而是在验证发生后我添加了自定义错误消息,我没有被重定向到原始表单。我缺少什么?

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();
} 

您可以像这样重定向回您来自的页面

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

因为你想被重定向到 原始形式 你必须定义验证失败时的行为,这样你就可以传递验证错误和调用方法的旧输入值 withErrorswithInput