跟我学Laravel之路由(3)
Route::filter('foo', 'FooFilter');
命名路由
重定向和生成URL时,使用命名路由会更方便。你可以为路由指定一个名字,如下所示:
Route::get('user/profile', array('as' => 'profile', function()
{
//
}));
还可以为 controller action指定路由名称:
现在,你可以使用路由名称来创建URL和重定向:
可以使用currentRouteName方法来获取当前运行的路由名称:
$name = Route::currentRouteName();
路由组
有时你可能需要为一组路由应用过滤器。使用路由组就可以避免单独为每个路由指定过滤器了:
Route::group(array('before' => 'auth'), function()
{
Route::get('/', function()
{
// Has Auth Filter
});
Route::get('user/profile', function()
{
// Has Auth Filter
});
});
子域名路由
Laravel中的路由功能还支持通配符子域名,你可以在域名中指定通配符参数:
注册子域名路由
Route::group(array('domain' => '{account}.myapp.com'), function()
{
Route::get('user/{id}', function($account, $id)
{
//
});
});
路由前缀
可以通过prefix属性为组路由设置前缀:
为路由组设置前缀
Route::group(array('prefix' => 'admin'), function()
{
Route::get('user', function()
{
//
});
});
路由与模型绑定
模型绑定,为在路由中注入模型实例提供了便捷的途径。例如,你可以向路由中注入匹配用户ID的整个模型实例,而不是仅仅注入用户ID。首先,使用 Route::model 方法指定要被注入的模型:
将参一个模型
Route::model('user', 'User');
然后,定义一个包含{user}参数的路由:
Route::get('profile/{user}', function(User $user)
{
//
});
由于我们已将{user}参数绑定到了User模型,因此可以向路由中注入一个User实例。例如,对profile/1的访问将会把ID为1的User实例注入到路由中。