Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
laravel怎么在Form Request验证器中获取路由参数_laravel Form Request验证器获取路由参数方法_创想鸟

laravel怎么在Form Request验证器中获取路由参数_laravel Form Request验证器获取路由参数方法

在 Laravel Form Request 中可通过 $this->route(‘参数名’) 获取路由参数,用于动态验证规则。例如更新用户时排除当前用户 ID 进行唯一性验证,使用 $this->route(‘id’) 获取 URL 中的 {id} 值,支持直接取参、获取 Route 实例或处理隐式绑定场景,适用于 email 唯一性等需动态排除自身记录的验证需求。

laravel怎么在form request验证器中获取路由参数_laravel form request验证器获取路由参数方法

在 Laravel 的 Form Request 验证器中获取路由参数,可以直接使用 $this->route() 方法。Laravel 将当前请求的路由实例注入到 Form Request 中,因此你可以通过它来访问 URL 中的动态参数。

1. 使用 $this->route() 获取路由参数

假设你的路由定义如下:

Route::put(‘/users/{id}’, [UserController::class, ‘update’]);

你在对应的 Form Request 类中可以通过以下方式获取 id 参数:

public function rules(){ $userId = $this->route(‘id’); return [ ’email’ => ‘required|email|unique:users,email,’ . $userId, ];}

$this->route(‘id’) 会自动从当前请求的路由中提取名为 id 的参数,常用于排除当前用户在唯一性验证中的场景。

2. route() 方法的多种用法

$this->route() 支持多种调用方式:

$this->route(‘id’):获取名为 id 的路由参数 $this->route():获取整个 Route 实例,可进一步调用其方法 $this->route()->parameter(‘id’):等同于 $this->route(‘id’) $this->route()->uri():获取原始路由 URI(如 users/{id})

3. 实际应用场景:更新用户时验证邮箱唯一性

例如,在更新用户时,需要验证邮箱唯一,但要排除当前用户自己:

阿里云-虚拟数字人 阿里云-虚拟数字人

阿里云-虚拟数字人是什么? …

阿里云-虚拟数字人 2 查看详情 阿里云-虚拟数字人 public function rules(){ $userId = $this->route(‘id’); // 或 $this->route()->parameter(‘user’) return [ ’email’ => ‘required|email|unique:users,email,’.$userId, ‘name’ => ‘required|string|max:255’, ];}

如果路由是 /users/5,那么 $this->route(‘id’) 返回的就是 5。

4. 路由参数名称与变量名不一致的情况

有时你在路由中定义了别名:

Route::put(‘/users/{id}’, …)->name(‘users.update’);// 或使用参数映射Route::bind(‘user’, User::class);

如果你使用了隐式绑定,比如:

Route::put(‘/users/{user}’, [UserController::class, ‘update’]);

那么你需要用 $this->route(‘user’) 来获取该参数。

基本上就这些。只要记住在 Form Request 中使用 $this->route(‘参数名’) 就能轻松获取路由参数,特别适用于结合唯一性验证等动态规则场景。不复杂但容易忽略。

以上就是laravel怎么在Form Request验证器中获取路由参数_laravel Form Request验证器获取路由参数方法的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/266536.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
怎么安装MySQL驱动程序
上一篇 2025年11月4日 10:43:07
生产力测试:专业软件中,RTX A6000与GeForce RTX 4090差距有多大?
下一篇 2025年11月4日 10:43:11

相关推荐

发表回复

登录后才能评论
关注微信