Laravel 5.6:如何通过Artisan命令根据URI获取匹配路由
如何通过URI快速匹配Laravel路由(自定义Artisan命令方案)
嘿,刚接触Laravel的话,这个需求确实很实用——直接通过请求URI定位对应的路由,比在route:list里翻找或者用筛选参数灵活多了。默认的route:list工具确实没有直接按URI匹配的参数,但我们有两种简单的方式实现这个功能:
方案一:用Tinker快速临时查询
如果你只是偶尔需要查一次,不用专门写命令,直接用Laravel的Tinker工具就能搞定:
- 打开终端,运行:
php artisan tinker - 在Tinker交互环境里,执行以下代码(把
blog/this-is-my-slug/换成你要查的URI):$route = app('router')->getRoutes()->match(request()->create('blog/this-is-my-slug/')); - 你可以打印路由的关键信息,比如:
// 查看路由名称 $route->getName(); // 查看对应的控制器方法 $route->getActionName(); // 查看允许的请求方法 $route->methods();
如果没有匹配到路由,会直接抛出NotFoundHttpException,提示没有找到对应路由。
方案二:自定义Artisan命令(推荐常用场景)
如果经常需要这个功能,自定义一个专属的Artisan命令会更方便,不用每次进Tinker。步骤如下:
1. 生成命令文件
运行以下命令生成一个新的Artisan命令:
php artisan make:command FindRouteByUri
2. 编写命令逻辑
打开生成的文件app/Console/Commands/FindRouteByUri.php,替换成以下代码:
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class FindRouteByUri extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'route:find {uri : The request URI to match against routes}'; /** * The console command description. * * @var string */ protected $description = 'Find the matching Laravel route for a given request URI'; /** * Execute the console command. */ public function handle() { $uri = $this->argument('uri'); // 创建模拟请求 $request = request()->create($uri); try { // 匹配路由 $route = $this->laravel->make('router')->getRoutes()->match($request); // 格式化输出路由信息 $this->info('✅ Found matching route:'); $this->table( ['Property', 'Details'], [ ['URI', $route->uri()], ['Route Name', $route->getName() ?: '*Unnamed Route*'], ['Allowed Methods', implode(', ', $route->methods())], ['Controller/Action', $route->getActionName()], ['Applied Middleware', implode(', ', $route->middleware())], ] ); } catch (NotFoundHttpException $e) { $this->error("❌ No route found matching URI: {$uri}"); } } }
3. 使用自定义命令
现在你可以直接在终端运行这个命令,传入要查询的URI:
php artisan route:find blog/this-is-my-slug/
执行后会以表格形式输出匹配到的路由的所有关键信息,清晰直观;如果没有匹配到,也会给出明确的错误提示。
注意事项
- URI可以带开头的
/也可以不带,request()->create()会自动处理这两种格式 - 如果你的路由有参数(比如
blog/{slug}),传入实际的slug值(如blog/this-is-my-slug/)也能正确匹配到对应的路由规则
内容的提问来源于stack exchange,提问作者climbd
相关产品推荐
相关产品推荐

