Laravel路由

来源:互联网 发布:js 获取滚动条位置 编辑:程序博客网 时间:2024/06/05 04:39

本文来自laravel文档,增加了自己的理解

其实文档很详细了。


什么是路由

  我的理解: 请求的链接。


基础路由

基本路由注册

大多数的路由设置都在app/Http/routes.php文件下。
1.Get

    Route::get('hello', function () {        //    });

2.Post

    Route::post('hello', function () {        //    });

3.Put

    Route::put('hello', function () {        //    });

其它的类似。

多重动作路由注册

对于一个URI,要写这么多很麻烦,可以使用match来简化

    Route::match(['get', 'post', 'put'], 'hello', function () {        //    });

路由参数

基础路由参数

URI经常会带有参数,我们肯定需要从中获取参数

    Route::get('/hello/{id}', function ($id) {        return $id;    });

这里设置了一个参数id,function中的参数名可以自己设置,它对应的值就是{id};假设现在访问localhost/hello/hi,页面会给出hi
当然参数可以是多个的。

可选的路由参数

    Route::get('hello/{id?}', function ($id = null) {        return $id;    });

在指定的参数后面添加?,就是可选的。

使用正则表达式对参数进行限制

有时候URI中带的参数需要规定格式、范围等等,可以使用正则表达式对其进行约束。

    Route::get('hello/{id}', function ($id) {        return $id;    })    ->where(['id' => '[0-9]+']);

通过where对参数进行约束,这里规定id参数必须为数字。

如果某个路由参数总是遵守正则表达式,可以使用pattern方法,在RouteServiceProviderboot方法里定义

 $router->pattern('id', '[0-9]+');

这样所有使用该参数名称的路由都会被应用。

命名路由

命名路由让你可以更方便的为特定路由生成 URL 或进行重定向。你可以使用as数组键指定名称到路由上:

Route::get('user/profile', ['as' => 'profile', function () {    //}]);

还可以指定路由名称到控制器动作:

Route::get('user/profile', [    'as' => 'profile',    'uses' => 'UserController@showProfile']);

除了可以在路由的数组定义中指定路由名称外,你也可以在路由定义后方链式调用name方法:

Route::get('user/profile', 'UserController@showProfile')->name('profile');

路由群组和命名路由

如果你使用了路由群组(将一些路由组成一个组,这些路由可以共用路由属性),那么你可以在路由群组的属性数组中指定一个as关键字,这将允许你为路由群组中的所有路由设置相同的前缀名称:

Route::group(['as' => 'admin::'], function () {    Route::get('dashboard', ['as' => 'dashboard', function () {        // 路由名称为「admin::dashboard」    }]);});

路由前缀

Route::group(['prefix' => 'admin'], function () {    Route::get('users', function ()    {        // 符合「/admin/users」URL    });});

使用prefix,之后访问就有个前缀admin;
当然也能指定共用的参数

Route::group(['prefix' => 'accounts/{account_id}'], function () {    Route::get('detail', function ($account_id)    {        // 符合 accounts/{account_id}/detail URL    });});
0 0
原创粉丝点击