1

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

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

对于每个获取请求的第二个参数。必须是数字。当我们创建资源时,问题就来了,如果我们使用->where()它会抛出一个关于 this is not an object 的错误。

我试图将 where 放入一个组中,作为第三个参数的数组。在资源中但没有工作。我们如何使用正则表达式的强大功能和 Laravel 4 资源的强大功能?

4

1 回答 1

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 的选项列表中,您可能不需要正则表达式检查。然而它是一个选项(正则表达式:模式)。

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

于 2014-03-12T10:18:48.793 回答