Laravel FormRequest验证失败时无法回传prepareForValidation修改的请求数据
Laravel独立FormRequest校验失败时,回传视图的参数不包含prepareForValidation改写值
问题背景
从控制器内联$request->validate()校验逻辑迁移到独立Request类实现校验的过程中,需要在校验流程启动前对部分请求参数做调整。通过框架提供的prepareForValidation()方法实现参数改写时,校验阶段可以正常读取到修改后的参数值;但校验失败重定向回创建页面后,视图中通过old()读取到的永远是prepareForValidation()执行前的原始请求值,而非改写后的内容。
预期流程
- 用户在标题输入框填写
ABCDEFG并点击保存按钮 - 请求在
prepareForValidation()阶段将标题值修改为Changed The Title - 校验未通过,用户被重定向回创建页面
- 标题输入框中显示修改后的
Changed The Title
实际表现
- 用户在标题输入框填写
ABCDEFG并点击保存按钮 - 请求在
prepareForValidation()阶段将标题值修改为Changed The Title - 校验未通过,用户被重定向回创建页面
- 标题输入框中显示用户原始输入的
ABCDEFG
已尝试的解决方案
为了在重定向回传时带上修改后的请求值,先后尝试了三种实现方式,均未达到预期:
- 将修改后的请求实例传入
ValidationException构造函数
查阅框架源码发现ValidationException支持传入响应类作为构造参数,编写的重写逻辑如下:
运行后触发报错:在protected function failedValidation(Validator $validator) { throw (new ValidationException($validator, $this)) ->errorBag($this->errorBag) ->redirectTo($this->getRedirectUrl()); }Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::addCookieToResponse位置出现Call to undefined method Symfony\Component\HttpFoundation\HeaderBag::setCookie()错误。 - 手动调用请求的
flash()方法将数据写入闪存Session
尝试手动触发请求闪存逻辑,期望将改写后的参数存入Session,重写逻辑如下:
实际功能未生效:Session中存储的依然是protected function failedValidation(Validator $validator) { $this->flash(); throw (new ValidationException($validator)) ->errorBag($this->errorBag) ->redirectTo($this->getRedirectUrl()); }prepareForValidation()执行之前的原始请求值,未读取到修改后的内容。 - 在
failedValidation()方法中直接返回带withInput()的重定向响应
不再抛出校验异常,直接返回携带错误和输入值的重定向响应,重写逻辑如下:
实际表现为框架没有中断执行流程,代码依然会继续进入protected function failedValidation(Validator $validator) { return redirect($this->getRedirectUrl()) ->withErrors($validator) ->withInput(); }BlogPostController::store()方法执行,不会触发重定向回视图的逻辑。
核心开发诉求
真实使用场景是处理active复选框的状态回传:该复选框在Blade模板中默认处于勾选状态,如果用户取消勾选后点击保存,HTTP请求中不会携带active字段,Laravel请求对象中不存在该值;当用户被重定向回页面时,复选框又回到了默认勾选状态,与用户的实际操作不符。示例中使用title字段做演示,是因为参数改写的效果更直观。
关联代码
BlogPostController.php
<?php namespace App\Http\Controllers; use App\BlogPost; use Illuminate\Http\Request; use App\Http\Requests\StoreBlogPost; class BlogPostController extends Controller { /** * Run the auth middleware to make sure the user is authorised. */ public function __construct() { $this->middleware('auth'); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('admin.blog-posts.create'); } /** * Store a newly created resource in storage. * * @param StoreBlogPost $request * @return \Illuminate\Http\Response */ public function store(StoreBlogPost $request) { $blogPost = BlogPost::create($request->all()); // Deal with the listing image upload if we have one. foreach ($request->input('listing_image', []) as $file) { $blogPost->addMedia(storage_path(getenv('DROPZONE_TEMP_DIRECTORY') . $file))->toMediaCollection('listing_image'); } // Deal with the main image upload if we have one. foreach ($request->input('main_image', []) as $file) { $blogPost->addMedia(storage_path(getenv('DROPZONE_TEMP_DIRECTORY') . $file))->toMediaCollection('main_image'); } return redirect()->route('blog-posts.edit', $blogPost->id) ->with('success', 'The blog post was successfully created.'); } } // Removed unrelated controller methods.
StoreBlogPost.php
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Contracts\Validation\Validator; use Illuminate\Validation\ValidationException; class StoreBlogPost extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'title' => 'required', 'url' => 'required', 'description' => 'required', 'content' => 'required', ]; } /** * Get the error messages for the defined validation rules. * * @return array */ public function messages() { return [ 'title.required' => 'The Title is required', 'url.required' => 'The URL is required', 'description.required' => 'The Description is required', 'content.required' => 'The Content is required', ]; } /** * Prepare the data for validation. * * @return void */ protected function prepareForValidation() { $this->merge([ 'active' => $this->active ?? 0, 'title' => 'Changed The Title', ]); } /** * @see FormRequest */ protected function failedValidation(Validator $validator) { throw (new ValidationException($validator)) ->errorBag($this->errorBag) ->redirectTo($this->getRedirectUrl()); } }
create.blade.php
@extends('admin.layouts.app') @section('content') <div class="edit"> <form action="{{ route('blog-posts.store') }}" method="POST" enctype="multipart/form-data"> @method('POST') @csrf <div class="container-fluid"> <div class="row menu-bar"> <div class="col"> <h1>Create a new Blog Post</h1> </div> <div class="col text-right"> <div class="btn-group" role="group" aria-label="Basic example"> <a href="{{ route('blog-posts.index') }}" class="btn btn-return"> <i class="fas fa-fw fa-chevron-left"></i> Back </a> <button type="submit" class="btn btn-save"> <i class="fas fa-fw fa-save"></i> Save </button> </div> </div> </div> </div> <div class="container-fluid"> <div class="form-group row"> <label for="content" class="col-12 col-xl-2 text-xl-right col-form-label">Active</label> <div class="col-12 col-xl-10"> <div class="custom-control custom-switch active-switch"> <input type="checkbox" name="active" value="1" id="active" class="custom-control-input" {{ old('active', '1') ? 'checked' : '' }}> <label class="custom-control-label" for="active"></label> </div> </div> </div> <div class="form-group row"> <label for="title" class="col-12 col-xl-2 text-xl-right col-form-label required">Title</label> <div class="col-12 col-xl-10"> <input type="text" name="title" id="title" class="form-control" value="{{ old('title', '') }}"> </div> </div> </div> </form> </div> @endsection
内容的提问来源于stack exchange,提问作者RobFos
相关产品推荐
相关产品推荐

