所有route被定义在app/Http/routes.php文件中,文件里包含最基础的route和group。默认的group是提供Web中间件的group。只有Web中间件内的Group才可以访问session以及CSRF保护。

Router允许注册的route类型包括:

Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);

如果需要同时满足多种请求类型,需要使用match方法,如果需要同时满足全部请求类型,使用any方法:

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

Route::any('foo', function () {
    //
});

Route可以从访问的url中获取参数:

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

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

参数中不允许包含-,只能使用_代替

我们也可以给route起名,方便在url中使用以及重定向。定义时使用'as'作为数组的key:

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

 

使用Controller的route也可以如下定义:

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

同时你可以在定义route时调用方法设置名字:

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

如果你使用了group,你可以使用as声明一个route名字前缀用于所有group内的route:

Route::group(['as' => 'admin::'], function () {
    Route::get('dashboard', ['as' => 'dashboard', function () {
        // Route named "admin::dashboard"
    }]);
});

定义名字后你就可以方便的使用了:

// Generating URLs...
$url = route('profile');

// Generating Redirects...
return redirect()->route('profile');

如果需要传参,你只需要像调用函数一样:

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

$url = route('profile', ['id' => 1]);

参数会被自动插入url的对应位置。

Route Group:

Route Group允许你共享属性给一组route,如middleware或者namespace。例子如下:

Route::group(['middleware' => 'auth'], function () {
    Route::get('/', function ()    {
        // Uses Auth Middleware
    });

    Route::get('user/profile', function () {
        // Uses Auth Middleware
    });
});

Route::group(['namespace' => 'Admin'], function()
{
    // Controllers Within The "App\Http\Controllers\Admin" Namespace

    Route::group(['namespace' => 'User'], function() {
        // Controllers Within The "App\Http\Controllers\Admin\User" Namespace
    });
});

默认的namespace目录为App\Http\Controllers。

同时也可以用route的group来匹配二级域名以及url前缀:

Route::group(['domain' => '{account}.myapp.com'], function () {
    Route::get('user/{id}', function ($account, $id) {
        //
    });
});

Route::group(['prefix' => 'admin'], function () {
    Route::get('users', function ()    {
        // Matches The "/admin/users" URL
    });
});

甚至可以在url前缀中加入参数:

Route::group(['prefix' => 'accounts/{account_id}'], function () {
    Route::get('detail', function ($accountId)    {
        // Matches The "/accounts/{account_id}/detail" URL
    });
});

 

posted on 2016-03-13 16:01  小虾ff  阅读(2001)  评论(0编辑  收藏  举报