修改app\Providers\RouteServiceProvider.php文件下的mapApiRoutes()为
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*
* @return void
*/
protected function mapApiRoutes()
{
$apiRoutes = Route::prefix('api')
->middleware('api')
->namespace($this->namespace);
//获取指定目录下的所有文件并根据文件创建路由组
array_map(function ($file) use ($apiRoutes) {
$apiRoutes->group($file);
}, self::getFilesArray(base_path('routes/api')));
}
并在mapApiRoutes()下添加如下方法
/**
* Search the route files from the dir.
* @param $searchDir
* @param array $files
* @return array
*/
private static function getFilesArray($searchDir, array &$files = []): array
{
//遍历目录下的所有文件和文件夹
$handle = opendir($searchDir);
while ($file = readdir($handle)) {
if ($file !== '..' && $file !== '.') {
$f = $searchDir . '/' . $file;
if (is_file($f)) {
//只取php文件
$extension = isset(pathinfo($file)['extension']) ? pathinfo($file)['extension'] : '';
if ($extension === 'php' || $extension === 'PHP') {
$files[] = $f;
}
} else {
//递归查询目录下的所有文件
self::getFilesArray($f, $files);
}
}
}
return $files;
}
这时你的api路由可以放在
routes\api\example1.php
or
routes\api\XXX\example1.php
....
有利于项目的路由分类,便于修改和查找