- 版本Laravel5.6
Laravel除了使用默認的路由文件來定義路由,還可以使用自己的路由文件。創(chuàng)建自己的路由文件步驟如下:
1.在routes文件夾下創(chuàng)建自己的路由文件,例如admin.php:

創(chuàng)建路由文件
2.在
app/Providers/RouteServiceProvider服務提供者中注冊該路由文件,添加mapAdminRoutes方法并且修改map方法,具體如下所示:
/**
* Define the "admin" routes for the application.
*/
protected function mapAdminRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/admin.php'));
}
示例中定義了路由文件的位置
routes/admin.php,除此之外你還可以規(guī)定路由的前綴prefix等。
/**
* Define the routes for the application.
*
* @return void
*/
public function map()
{
$this->mapApiRoutes();
$this->mapWebRoutes();
$this->mapAdminRoutes();
}
3.在路由文件admin.php中添加路由:
<?php
Route::group(['prefix' => 'admin', 'namespace' => 'Admin'], function() {
Route::get('index', 'IndexController@index');
Route::get('test', function() {
return 'your route is ready';
});
});
示例在路由群組中創(chuàng)建了兩條路由,index和test,因為規(guī)定了前綴和命名空間,所以這兩條路有的訪問方式是/admin/index和/admin/test,加上所在的域名即可,例如我的域名為cms.choel.com,所以路由分別是cms.choel.com/admin/index和cms.choel.com/admin/test。
注:
admin/index路由會訪問Admin/Index/index方法(文件路徑app/Http/Controller/Admin/IndexConrtoller.php中的index方法),而admin/test會執(zhí)行閉包函數(shù)直接打印your route is ready,下面是index方法中的測試代碼。
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
class IndexController extends Controller
{
public function index() {
var_dump('ok');
}
}
示例結(jié)果如下:

路由admin/index

路由admin/test
由于本人學藝不精,未盡之處還望海涵,有誤之處請多多指正,歡迎大家批評指教
全文 完