Laravel里面有4个默认的路由文件,其中web.php是默认路由文件,如果需要添加其他路由文件,需要自行添加,按照以下步骤进行。
所有 Laravel 路由都定义在位于 routes
目录下的路由文件中,这些文件通过框架自动加载,相应逻辑位于 app/Providers/RouteServiceProvider,我们找到相对应的文件
1:首先修改/app/providers/RouteServiceProvider.php,代码如下
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Route;
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.
*
* @return void
*/
public function boot()
{
//
parent::boot();
}
/**
* Define the routes for the application.
*
* @return void
*/
public function map()
{
$this->mapApiRoutes();
$this->mapWebRoutes();
//添加执行的路由方法
$this->mapAdminRoutes();
}
/**
* 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'));
}
//添加路由方法
protected function mapAdminRoutes()
{
Route::prefix('admin')
->group(base_path('routes/admin.php')); //表示routes/admin.php文件
}
}
2:在route文件里面新建admin.php文件代码如下 route/admin.php
<?php
//路由组 表示在App\Http\Controllers\Admin路径 默认前缀为admin
Route::group(["namespace" => "App\Http\Controllers\Admin", "middleware" => "api"], function () {
/**********************************后台路由**********************************************/
Route::get('/', "IndexController@index");
});
3:在路由组 表示在App\Http\Controllers里面新建文件夹Admin
4:创建控制器 手动创建或者使用artisan命令 php artisan make:controller Admin/IndexController
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class IndexController extends Controller
{
//
public function index(){
echo '访问成功';
}
}
5:访问路由查看是否成功