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

Laravel日期验证出现Undefined variable: request错误如何解决?

错误原因

你遇到的Undefined variable: request报错是因为PHP闭包默认无法直接访问父作用域的变量,你在自定义验证规则的匿名函数里使用了$request,但没有将它导入到闭包作用域中。

解决方法

1. 快速修复闭包作用域问题

只需要在闭包声明处用use关键字引入$request即可,修改后的验证规则如下:

'date_of_birth'=>['required','bail','date_format:Y-m-d',function ($attribute, $value, $fail) use ($request) {
    $age=Carbon::createFromFormat('Y-m-d', $value)->diff(Carbon::now())->y;
    if($age<18||$age>70){
        $date = str_replace('-', '/', $value);
        $new_bday=date("d/m/Y", strtotime($date) );
        $request->merge(['date_of_birth' => $new_bday]);
        $fail('Âge invalide. l\'âge devrait être 18-70');
    }
},]

2. 更规范的回显处理方案(可选)

你不需要在验证逻辑里修改$request的值来适配前端回显,更合理的方式是在前端回显的时候统一处理日期格式,和业务逻辑解耦。如果使用Blade模板,可直接在视图层做格式转换:

<input type="text" name="date_of_birth" value="{{ old('date_of_birth') ? \Carbon\Carbon::parse(old('date_of_birth'))->format('d/m/Y') : '' }}">

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 15:24:10