laravel本身自带4个路由,如果你自定义一个路由文件,直接写肯定是不行的,因为laravel
路由需要在/App/Providers/RouteServiceProvider.php
中map
方法中注册,只需要两步就可以自定义路由
首先需要新建一个自定义的路由文件,可以是项目里任何一个位置,这里我就新建了一个js.api.php
文件,在使用注册路由前,先引入use Illuminate\Support\Facades\Route;
,在laravel中,所有路由得使用Route
类注册才能生效.
接下来打开/App/Providers/RouteServiceProvider.php
,如下列代码所示
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;
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';
/**
* The path to the "home" route for your application.
*
* @var string
*/
public const HOME = '/home';
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
//
parent::boot();
}
/**
* Define the routes for the application.
*
* @return void
*/
public function map()
{
$this->mapApiRoutes();
$this->mapWebRoutes();
$this->mapMyApiRoutes();
}
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* @return void
*/
protected function mapWebRoutes()
{
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'));
}
/**
* Custom application API routing.
*
* These routes are typically stateless.
*
* @return void
*/
protected function mapMyApiRoutes()
{
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/js.api.php'));
}
}
自定义一个在RouteServiceProvider.php中自定义一个路由方法,规范如下:
/**
* Custom application API routing.
*
* These routes are typically stateless.
*
* @return void
*/
protected function mapMyApiRoutes()
{
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/js.api.php'));
}
因为我注册的是api的路由,所以前缀prefix
和中间件middleware
都是api,命名空间namespace
中参数可以是自己控制器的命名空间,分组group
参数就是你自定义路由文件的位置,确认没问题后,最后在RouteServiceProvider.php
中map方法中调用你刚刚新建的方法即可,如下列代码所示
/**
* Define the routes for the application.
*
* @return void
*/
public function map()
{
$this->mapMyApiRoutes();
}
这样注册后,就可以愉快得在自己新建的路由文件里注册路由了,最后,可以使用命令行中(命令行的打开的文件位置一定要是项目根目录)使用php ./artisan route:list
,查看注册的路由