You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 10如何将请求验证文件的参数传递回上一个视图

Laravel验证失败重定向时传递自定义参数的解决方案

问题场景

在Laravel中创建了UpdatePasswordRequest请求文件并配置了验证规则,希望在验证失败重定向回上一视图时,传递自定义参数['tab' => 'updatePassword'],并通过old('tab')在视图中获取。但尝试在withValidator方法中添加重定向逻辑后无法生效。

原因分析

withValidator是FormRequest提供的验证钩子,仅用于添加额外验证逻辑,它的返回值不会被框架处理,因此你在该方法中返回的重定向不会覆盖框架默认的验证失败流程。

解决方案

重写FormRequest的failedValidation方法,自定义验证失败时的重定向逻辑,将自定义参数加入到输入数据中,这样就能通过old('tab')获取到该值。

修改后的UpdatePasswordRequest代码

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\ValidationException;

class UpdatePasswordRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'password' => 'required',
            'newPassword' => [
                'required', 'string', 'min:10', 'regex:/[a-z]/', 'regex:/[A-Z]/', 'regex:/[0-9]/', 'regex:/[@$!%*#?&]/',
            ],
            'confirmPassword' => 'required',
        ];
    }
    
    public function messages(): array
    {
        return [
            'password.same' => 'password doesn\'t match with the current password',
            'newPassword.min' => 'new password must be at least 10 digits',
            'newPassword.regex' => "<ul><li>must contain at least one lowercase letter</li>
                                    <li>must contain at least one uppercase letter</li>
                                    <li>must contain at least one digit</li>
                                    <li>must contain a special character for example [* # & %]</li></ul>",
        ];
    }

    protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
    {
        // 将自定义参数合并到请求输入中
        $this->merge(['tab' => 'updatePassword']);
        
        // 调用父类默认的验证失败处理逻辑,自动重定向并携带输入数据
        parent::failedValidation($validator);
    }
}

另一种自定义重定向的写法

如果需要更灵活控制重定向逻辑,也可以直接构建ValidationException:

protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
{
    throw ValidationException::withMessages($validator->errors()->messages())
        ->redirectTo(redirect()->back()->getTargetUrl())
        ->withInput(array_merge($this->input(), ['tab' => 'updatePassword']));
}

验证生效后,在视图中即可通过old('tab')获取到updatePassword值。

内容的提问来源于stack exchange,提问作者Kareem Zayed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 03:24:58