route regex检查数据库中是否存在id

时间:2013-05-31 09:22:45

标签: php laravel laravel-4

如果您只想接受路线的特定参数,请执行以下操作:

Route::get('users/{id}', 'UsersController@show')->where('id', '\d+');

但是,如果我想要这样的东西:

Route::get('users/{id}', 'UsersController@show')->where('id', '\d+')->where(this id exists in table column id);

laravel怎么可能? 如果数据库中不存在id,我想返回找不到的页面。


更新

我有创建过滤器的想法:

Route::filter('user.exists', function()
{
//get the id then check the database
});

但是如何将$ id传递给过滤器?


注释

我知道我可以做一些检查,如果查询返回控制器中的任何数据,如果现在就抛出404:

$user = User::find($id);

if(!$user){
    App::abort(404);
}

但我认为如果我能在路线本身做到这一点会更清洁。因为我有更多的东西不仅可以过滤用户。

1 个答案:

答案 0 :(得分:1)

这应该有助于您入门:

Route::get('users/{id}', 'UsersController@show', array('before' => 'userExists'))->where('id', '[\d]+');

Route::filter('userExists', function($id) {
  echo $id; exit;
});
相关问题