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

如何在Laravel请求对象中添加自定义验证逻辑?

Laravel请求对象中实现自定义验证的正确方式

你的代码问题在于自定义的after方法不会被Laravel自动调用,需要使用框架提供的withValidator钩子来添加验证后的逻辑。以下是修正后的完整代码:

<?php

namespace App\Http\Requests\Event;

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

class EventRequest 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 [
            "event_name" => "required|unique:events|max:255",
            "company_id" => "exists:companies",
            "start_date" => "required|regex:/^\d{4}-\d{2}-\d{2}$/",
            "start_time" => "regex:/^\d{2}:\d{2}$/",
            "end_date" => "required|regex:/^\d{4}-\d{2}-\d{2}$/",
            "end_time" => "regex:/^\d{2}:\d{2}$/",
        ];
    }

    /**
     * 自定义验证后逻辑
     *
     * @param  Validator  $validator
     * @return void
     */
    public function withValidator(Validator $validator)
    {
        $validator->after(function (Validator $validator) {
            // 获取所有请求数据,替代safe()(safe()需验证通过后才能调用)
            $data = $this->all();

            foreach ($data as $key => $value) {
                // 检查类似title:en、title:sk这类字段的长度
                if (str_contains($key, 'title') && !empty($value) && strlen($value) > 250) {
                    // 错误信息关联到具体字段,而非统一的title字段
                    $validator->errors()->add($key, "$key 长度不能超过250个字符");
                }
            }
        });
    }
}

关键修改点:

  • 移除自定义的after方法,改用Laravel FormRequest内置的withValidator方法,框架会自动调用这个方法传递验证器实例
  • 将$validator->safe()替换为$this->all(),因为safe()是验证通过后才生成的安全数据集合,在after回调中还未生成
  • 将错误信息关联到具体的字段(如title:en),而非统一的title字段,这样前端能精准定位错误位置

内容的提问来源于stack exchange,提问作者Čamo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 15:30:00