Laravel新建路由文件

作者: 从入门到颈椎病 | 来源:发表于2018-06-18 01:34 被阅读35次
  • 版本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';
    });
});

示例在路由群组中创建了两条路由,indextest,因为规定了前缀和命名空间,所以这两条路有的访问方式是/admin/index/admin/test,加上所在的域名即可,例如我的域名为cms.choel.com,所以路由分别是cms.choel.com/admin/indexcms.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');
    }
}

示例结果如下:


路由admin/index
路由admin/test

由于本人学艺不精,未尽之处还望海涵,有误之处请多多指正,欢迎大家批评指教

全文 完

相关文章

网友评论

    本文标题:Laravel新建路由文件

    本文链接:https://www.haomeiwen.com/subject/fjsgeftx.html