2013-06-02 24 views
0

如果我们使用Laravel 4创建简单路由,我们可以使用在哪里为每个参数设置正则表达式。通过URI传递。例如:如何在Laravel 4中使用正则表达式与资源

Route::get('users/{id}',function($id){ 
    return $id; 
})->where('id','\d+'); 

对于每个获取请求第二个参数。必须是数字。当我们创建资源时会出现问题,如果我们使用->where()它会抛出关于这个不是对象的错误。

我试过把它放到组中,作为第三个参数的数组。在资源中,但没有工作。我们如何利用Laravel 4资源的力量使用正则表达式的力量?

+0

不要*想*你可以。您应该进行检查以确保所提供的值存在于数据库中,因此确保它只是一个数字,或者只包含字母数字字符不总是*必需的。 –

回答

0

何乔斯,

我发疯的同一个问题,所以我做了一些研究。我所能得出的结论是:你不需要这种方法。在您的每一个控制器方法,你可以在每个参数后指定默认值:

public function getPage(id = '0', name = 'John Doe'){ 

下一页到这一点,你可以做一个正则表达式检查,很多与laravel验证这样的其他检查:

 //put the passed arguments in an array 
      $data['id'] = $id; 
      $data['name'] = $name; 

    //set your validation rules 
      $rules = array(
        "id" => "integer" 
        "name" => "alpha" 
     ); 
      // makes a new validator instance with the data to be checked with the given 
      // rules 
    $validator = Validator::make($data, $rules); 

      // use the boolean method passes() to check if the data passes the validator 
    if($validator->passes()){ 
      return "stuff"; 
      } 

      // set a error response that shows the user what's going on or in case of    
      // debugging, a response that confirms your above averages awesomeness 

      return "failure the give a response Sire"; 
} 

由于大多数验证已经在laravel的options list中,因此您可能不需要进行正则表达式检查。但它是一个选项(正则表达式:模式)。

我的理论背后没有存在控制器中的where()方法,该方法为您提供了在您的路径文件中进行验证的机会。既然你已经在你的控制器中有这种可能性,那么就没有必要这么做了。

相关问题