我创建了一个新的服务提供商,需要在其中获取所有注册的路由。但是Route::getRoutes()->getIterator()
返回null
。
这是我的完整代码,
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Foundation\Application;
use Illuminate\Support\Facades\Request;
class ApiVersionServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to your controller routes.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\Http\Controllers';
public function register()
{
if (Request::instance()->is('api/v*')) {
$routes = [];
foreach (Route::getRoutes()->getIterator() as $route) {
if ((strpos($route->uri, 'api') !== FALSE) AND basename($route->uri) == basename(Request::instance()->path())) {
$routes[] = $route->uri;
}
}
dd($routes);
}
}
}
在这里可以找到路线吗?
答案 0 :(得分:4)
根据文档:https://laravel.com/docs/5.6/providers#the-boot-method
您应将代码放在boot()
方法内。
在所有其他服务提供商都注册之后,将调用此方法
当前,您正在尝试使用路由服务进行自身注册。
因此它应该看起来像:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Foundation\Application;
use Illuminate\Support\Facades\Request;
class ApiVersionServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to your controller routes.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\Http\Controllers';
/**
* Using boot method to ensure it is executed when the Route service is ready to be used
*/
public function boot()
{
if (Request::instance()->is('api/v*')) {
$routes = [];
foreach (Route::getRoutes()->getIterator() as $route) {
if ((strpos($route->uri, 'api') !== FALSE) AND basename($route->uri) == basename(Request::instance()->path())) {
$routes[] = $route->uri;
}
}
// Do anything you need with $routes array.
}
}
}