【问题标题】:route regex check if id exists in database路由正则表达式检查数据库中是否存在id
【发布时间】:2013-06-01 03:20:38
【问题描述】:

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

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 做到这一点?
如果 db 中尚不存在 id,我想返回未找到的页面。


更新

我有一个想法来创建一个过滤器:

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

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


注意

我知道我可以做一些事情,比如检查查询是否在控制器中返回了任何数据,如果现在像这样,则抛出 404:

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

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

但我认为如果我可以在路线本身中执行此操作会更清洁。因为我不仅要过滤用户。

【问题讨论】:

    标签: php laravel laravel-4


    【解决方案1】:

    这应该可以帮助您入门:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-29
      • 2010-10-22
      • 1970-01-01
      • 2014-07-21
      • 2021-03-19
      • 2018-12-12
      相关资源
      最近更新 更多