- 版本Laravel5.6
Laravel除了使用默认的路由文件来定义路由,还可以使用自己的路由文件。创建自己的路由文件步骤如下:
1.在routes
文件夹下创建自己的路由文件,例如admin.php
:
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
,除此之外你还可以规定路由的前缀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';
});
});
示例在路由群组中创建了两条路由,index
和test
,因为规定了前缀和命名空间,所以这两条路有的访问方式是/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
会执行闭包函数直接打印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');
}
}
示例结果如下:
由于本人学艺不精,未尽之处还望海涵,有误之处请多多指正,欢迎大家批评指教
全文 完