如何为Laravel的Route::resource()方法添加元数据?
实现Route::resource()支持descriptions参数
步骤1:扩展PendingResourceRegistration类
在app/Providers/RouteServiceProvider.php的boot方法中,补充以下代码,为资源路由注册类添加描述支持:
use Illuminate\Routing\PendingResourceRegistration; public function boot() { // 你已实现的单个路由描述宏 \Illuminate\Routing\Route::macro('addDescription', function ($description) { $this->action['meta']['description'] = $description; return $this; }); \Illuminate\Routing\Route::macro('getDescription', function () { return $this->getAction('meta.description'); }); // 为资源路由添加descriptions批量设置功能 PendingResourceRegistration::macro('descriptions', function (array $descriptions) { // 暂存描述配置 $this->options['descriptions'] = $descriptions; // 包装原生注册方法,完成路由注册后批量设置描述 $originalRegister = $this->register; $this->register = function () use ($originalRegister, $descriptions) { $routeCollection = $originalRegister(); // 遍历所有注册完成的资源路由 foreach ($routeCollection as $route) { $routeName = $route->getName(); if (!$routeName) continue; // 拆分路由名称,如"posts.index"拆分为["posts", "index"] [$resource, $action] = explode('.', $routeName); // 匹配对应动作的描述并设置 if (isset($descriptions[$action])) { $route->addDescription($descriptions[$action]); } } return $routeCollection; }); return $this; }); }
步骤2:使用descriptions参数注册资源路由
现在可以像使用names参数一样,为资源路由的每个动作设置描述:
Route::resource('posts', PostController::class)->descriptions([ 'index' => '展示所有文章列表', 'show' => '展示单篇文章详情', 'create' => '展示文章创建表单', 'store' => '保存新创建的文章', 'edit' => '展示文章编辑表单', 'update' => '更新指定文章', 'destroy' => '删除指定文章', ]);
步骤3:获取路由描述
通过之前定义的getDescription方法,可随时获取路由的描述信息:
// 获取指定路由的描述 $indexDescription = Route::getRouteByName('posts.index')->getDescription(); // 在控制器中获取当前路由的描述 $currentDescription = request()->route()->getDescription();
内容的提问来源于stack exchange,提问作者Sharif Khan
相关产品推荐
相关产品推荐

