Laravel学习2:Routing(路由)

官方文档地址:https://docs.golaravel.com/docs/5.5/routing/

首先我的Laravel版本为5.5.43,系统为windows。

找到5.5版本的路由配置文件。

Laravel学习2:Routing(路由)

框架默认加载了routes/web.php和routes/api.php(打开web.php)

Laravel学习2:Routing(路由)

1.基本路由

请求地址 http://localhost/yangdj1/my_laravel/public/


Route::get('/', function () {
    return view('welcome');
});

请求地址 http://localhost/yangdj1/my_laravel/public/user

Route::get('/user', '[email protected]');

允许请求路由类型:get,post,put,patch,delete,options,any,match

CSRF Protection

其中post,put,delete页面请求路由类型时需要需要包含CSRF Protection(跨站qing请求保护)

<form method="POST" action="/profile">
    {{ csrf_field() }}
    ...
</form>

Redirect Routes(重定向路由)

Route::redirect('/here', '/there', 301);

View Routes(视图路由)

/**
 * 
 */
Route::view('/welcome', 'welcome');
/**
 * 此外,还可以提供一组数据作为可选的第三个参数传递给视图
 */
Route::view('/welcome', 'welcome', ['name' => 'Taylor']);

2.Route Parameters(路由参数)

路由参数总是包含在{}括号内,并且应该由字母字符组成。不可以包含字符"-",可以使用"_"字符代替"-"字符。路由参数根据其顺序注入到控制器或回调函数中,而不是由回调函数或控制器的参数决定的。

required Parameters(包含参数)

比如想要获取用户详情时需要捕获到URL中的用户ID,你可以参照以下做法:

Route::get('user/{id}', function ($id) {
    return 'User '.$id;
});

当然,也可捕获多个路由参数,例如:

Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {
    //
});

Optional Parameters(可选参数)

有的时候,你需要指定路由参数,但是参数不是必填的,cish此时可以使用"?"字符在参数名后做一个标记,确保给路由的相应变量提供默认值。

Route::get('user/{name?}', function ($name = null) {
    return $name;
});
Route::get('user/{name?}', function ($name = 'Tom') {
    return $name;
});

 

Regular Expression Constraints(正则表达式约束)

可以使用where来约束你的路由参数格式。where方法接受参数的名称和定义参数格式正则表达式(注:where参数可以用数组形式,从而达到限制多个路由参数的目的)

Route::get('user/{name}', function ($name) {
    //name只能为字母字符(包含大小写)
})->where('name', '[A-Za-z]+');

Route::get('user/{id}', function ($id) {
    //id只能为数字
})->where('id', '[0-9]+');

Route::get('user/{id}/{name}', function ($id, $name) {
    //同一时间捕获两个路由参数,id只能为数字,name只能为小写字母字符
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);

Global Constraints(全局约束)

如果需要路由参数一直受到正则表达式约束,可以使用"pattern" 。你需要在 RouteServiceProvider 文件中的boot方法中注册路由,例如:

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        //约束id只能为数字
        Route::pattern('id', '[0-9]+');
        parent::boot();
    }

一但定义了全局约束,它就会自动应用到所有路由的该参数名。

Route::get('user/{id}', function ($id) {
    // 当id为数字字符时执行
});

Named Routes(命名路由)

 

 

未完待续...