Php 如何将正则表达式与Laravel 4中的资源一起使用

Php 如何将正则表达式与Laravel 4中的资源一起使用,php,routes,laravel,laravel-4,Php,Routes,Laravel,Laravel 4,如果我们用Laravel 4创建一个简单路由,我们可以使用where为每个参数设置一个正则表达式。传入URI。例如: Route::get('users/{id}',function($id){ return $id; })->where('id','\d+'); 对于每个get请求,使用第二个参数。必须是数字。当我们创建资源时会出现问题,如果我们使用->where()它会抛出一个关于这不是对象的错误 我试着将where放入一个组,作为数组作为第三个参数。在资源中,但没有起作用。

如果我们用Laravel 4创建一个简单路由,我们可以使用where为每个参数设置一个正则表达式。传入URI。例如:

Route::get('users/{id}',function($id){
    return $id;
})->where('id','\d+');
对于每个get请求,使用第二个参数。必须是数字。当我们创建资源时会出现问题,如果我们使用
->where()
它会抛出一个关于这不是对象的错误

我试着将where放入一个组,作为数组作为第三个参数。在资源中,但没有起作用。我们如何将正则表达式的功能与Laravel 4资源的功能结合起来使用?

He Joss

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

public function getPage(id = '0', name = 'John Doe'){
接下来,您可以使用laravel validator执行正则表达式检查和许多其他检查,如下所示:

        //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中,您可能不需要正则表达式检查。但这是一种选择(regex:pattern)

我认为控制器中不存在where()方法的理论是,该方法为您提供了在路由文件中进行验证的机会。由于您的控制器中已经存在这种可能性,因此不需要它

别以为你能。您应该进行检查,以确保提供的值在数据库中存在,因此确保它仅为数字或仅包含字母数字字符并不总是必需的。