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

Laravel 9调用FormRequest::withValidator方法抛出方法不存在错误

Laravel FormRequest withValidator 方法报错排查

问题场景

编写带withValidator()方法的FormRequest类,参照官方文档编写代码后执行报错。

相关代码

<?php

namespace App\Http\Requests\Conversation;

use Illuminate\Foundation\Http\FormRequest;

class StoreConversationRequest 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<string, mixed>
     */
    public function rules()
    {
        return [
            'type' => 'required|in:text,media',
            'text' => 'required_if:type,text|string',
            'medias' => 'required_if:type,media|array',
            'medias.*' => 'file|max:5120|mimes:jpg,jpeg,png,pdf,mp3,mp4',
            'phone' => 'required|numeric',
            'conversation' => 'required|exists:conversations,id',
        ];
    }
    
    /**
     * Configure the validator instance.
     *
     * @param  \Illuminate\Validation\Validator  $validator
     * @return void
     */
    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            if ($this->somethingElseIsInvalid()) {
                $validator->errors()->add('field', 'Something is wrong with this field!');
            }
        });
    }
}

报错信息

初始报错:

Method App\Http\Requests\Conversation\StoreConversationRequest::somethingElseIsInvalid does not exist.

将闭包内$this替换为$validator后依然报错:

Method Illuminate\Validation\Validator::somethingElseIsInvalid does not exist.

错误原因

somethingElseIsInvalid()是Laravel文档里用来演示后置校验用法的占位示例方法,不是框架内置的真实方法。直接复制示例代码没有替换成自己的业务判断,不管是当前FormRequest类还是验证器类都不存在这个方法,自然会抛出方法不存在的错误。

修复方案

  • 无额外自定义校验需求:直接删除整个withValidator方法即可正常运行。
  • 需要添加自定义后置校验:将占位的方法判断替换为实际业务逻辑即可,参考示例:
public function withValidator($validator)
{
    $validator->after(function ($validator) {
        // 示例逻辑:文本类型消息内容长度不能超过500字,可替换为自身业务规则
        if ($this->type === 'text' && mb_strlen($this->text) > 500) {
            $validator->errors()->add('text', '文本内容长度不能超过500个字符');
        }
    });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 01:45:46