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的路由即可访问相关接口。
扫描二维码关注公众号,回复:
3995887 查看本文章
附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'));
}
}