使用其他中介軟體新增 api-routes 並保留預設的 Web 中介軟體
自 Laravel 版本 5.2.31 以來,Web 中介軟體預設應用於 RouteServiceProvider( https://github.com/laravel/laravel/commit/5c30c98db96459b4cc878d085490e4677b0b67ed)
在 app / Providers / RouteServiceProvider.php 中,你將找到以下函式,這些函式在 app / Http / routes.php 中的每個路徑上應用中介軟體。
public function map(Router $router)
{
$this->mapWebRoutes($router);
}
// ...
protected function mapWebRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'web',
], function ($router) {
require app_path('Http/routes.php');
});
}
如你所見,應用了中介軟體 Web。你可以在這裡改變它。但是,你也可以輕鬆新增另一個條目,以便將你的 api 路由放到另一個檔案中(例如 routes-api.php)
public function map(Router $router)
{
$this->mapWebRoutes($router);
$this->mapApiRoutes($router);
}
protected function mapWebRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'web',
], function ($router) {
require app_path('Http/routes.php');
});
}
protected function mapApiRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'api',
], function ($router) {
require app_path('Http/routes-api.php');
});
}
有了這個,你可以輕鬆地從應用程式路徑中分離 api 路由,而不會在 routes.php 中使用混亂的組包裝器