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

在 Laravel 的 Form Request 验证器中获取路由参数,可以直接使用 $this->route() 方法。Laravel 将当前请求的路由实例注入到 Form Request 中,因此你可以通过它来访问 URL 中的动态参数。
假设你的路由定义如下:
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 的参数,常用于排除当前用户在唯一性验证中的场景。
$this->route() 支持多种调用方式:
例如,在更新用户时,需要验证邮箱唯一,但要排除当前用户自己:
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。
有时你在路由中定义了别名:
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验证器获取路由参数方法的详细内容,更多请关注php中文网其它相关文章!
 
                 
                                
                                 收藏
收藏
                                                                             
                                
                                 收藏
收藏
                                                                             
                                
                                 收藏
收藏
                                                                            Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号