美文网首页
PHP Laravel学习路由之参数、命名和分组

PHP Laravel学习路由之参数、命名和分组

作者: 唐朝早晨 | 来源:发表于2018-07-18 19:44 被阅读0次

官方文档传送门:http://laravelacademy.org/post/7769.html


路由参数

必选参数

从路由里获取URL的请求参数:以获取id为例定义如下:
Route::get('user/{id}', function (id) { return 'User ' .id;
});
在浏览器里访问user/1就可以得到:User 1;
定义多个参数:
Route::ger('posts'/{post},'comments'/{comment},function($postId,$commentId){
return $postId. '-'.$commentId;
});

可选参数:

有必选参数就有可选参数,这可以通过在参数名后加一个 ? 标记来实现,这种情况下需要给相应的变量指定默认值,当对应的路由参数为空时,使用默认值。
Route::get('user/{name?}', function ($name = null) {
return $name;
}); //output:空
Route::get('user/{name?}', function ($name = 'John') {
return $name; //output:John
});

正则约束
通过使用正则表达式来约束路由的参数,基本定义:
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]+']);

路由命名

命名路由为生成 URL 或重定向提供了方便,实现起来也很简单,在路由定义之后使用 name 方法链的方式来定义该路由的名称:

Route::get('user/profile', function () {
    // 通过路由名称生成 URL
    return 'my url: ' . route('profile');
})->name('profile');

//还可以为控制器动作指定路由名称:
Route::get('user/profile', 'UserController@showProfile')->name('profile');
Route::get('redirect', function() {
    // 通过路由名称进行重定向
    return redirect()->route('profile');
});
//为路由生成URL
$url = route('profile');
//在URL里传参
$url = route('profile', ['id' => 1]);

路由分组

路由分组的目的是让我们在多个路由中共享相同的路由属性,比如中间件和命名空间等,这样的话我们定义了大量的路由时就不必为每一个路由单独定义属性。共享属性以数组的形式作为第一个参数被传递给 Route::group 方法。

要给某个路由分组中定义的所有路由分配中间件,可以在定义分组之前使用 middleware 方法。中间件将会按照数组中定义的顺序依次执行:

Route::middleware(['first', 'second'])->group(function () {
    Route::get('/', function () {
        // Uses first & second Middleware
    });

    Route::get('user/profile', function () {
        // Uses first & second Middleware
    });
});
//当访问这个分组里的路由时,先执行中间件执行完中间件然后执行路由;
···
路由分组另一个通用的例子是使用 namespace 方法分配同一个 PHP 命名空间给该分组下的多个控制器:
···
Route::namespace('Admin')->group(function () {
    // Controllers Within The "App\Http\Controllers\Admin" Namespace
});
···

相关文章

网友评论

      本文标题:PHP Laravel学习路由之参数、命名和分组

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