laravel中新增路由檔案
阿新 • • 發佈:2018-11-09
laravel版本是 5.4.36(使用命令 php artisan --version檢視),專案中本來只有一個routes.php(路徑是app/Http/routes.php),現在想要建多個路由檔案,為了便於管理路由。
可以分三步完成:
1、在專案根目錄下建立一個routes資料夾,下面再分別建立兩個檔案web.php和api.php,結構如下:
2、以api.php檔案為例,在app/Providers/RouteServiceProvider.php中新增函式:
/** * Define the "api" routes for the application. * * These routes are typically stateless. * * @return void */ protected function mapApiRoutes() { Route::prefix('api') ->middleware('api') ->namespace($this->namespace) ->group(base_path('routes/api.php')); }
修改本檔案中的map方法(新增一句話):
$this->mapApiRoutes();
3、在api檔案中新增路由,如:
Route::group(['prefix' =>'test2','namespace' => 'Api\Test'], function () { Route::resource('main', 'TestController'); });
輸入/api/test2/main的路由即可訪問相關介面。
附app/Providers/RouteServiceProvider.php檔案完整程式碼:
<?php namespace App\Providers; use Illuminate\Support\Facades\Route; use Illuminate\Routing\Router; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; class RouteServiceProvider 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'; /** * Define your route model bindings, pattern filters, etc. * * @param \Illuminate\Routing\Router $router * @return void */ public function boot() { // parent::boot(); } /** * Define the routes for the application. * * @param \Illuminate\Routing\Router $router * @return void */ public function map(Router $router) { $this->mapWebRoutes($router); $this->mapWeb2Routes(); $this->mapApiRoutes(); // } /** * Define the "web" routes for the application. * * These routes all receive session state, CSRF protection, etc. * * @param \Illuminate\Routing\Router $router * @return void */ protected function mapWebRoutes(Router $router) { $router->group([ 'namespace' => $this->namespace, 'middleware' => 'web', ], function ($router) { require app_path('Http/routes.php'); }); } /** * Define the "web" routes for the application. * * These routes all receive session state, CSRF protection, etc. * * @return void */ protected function mapWeb2Routes() { Route::middleware('web') ->namespace($this->namespace) ->group(base_path('routes/web.php')); } /** * Define the "api" routes for the application. * * These routes are typically stateless. * * @return void */ protected function mapApiRoutes() { Route::prefix('api') ->middleware('api') ->namespace($this->namespace) ->group(base_path('routes/api.php')); } }