【问题标题】:How to use regular expressions with resources in Laravel 4如何在 Laravel 4 中使用正则表达式和资源
【发布时间】:2013-05-28 15:49:52
【问题描述】:

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

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

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

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

【问题讨论】:

  • 不要认为你可以。您应该进行检查以确保所提供的值无论如何都存在于数据库中,因此确保它只是一个数字或只包含字母数字字符不是总是必需的。

标签: php routes laravel laravel-4


【解决方案1】:

何乔斯,

我对同样的问题很生气,所以我做了一些研究。我只能得出以下结论:您不需要这种方法。在每个控制器方法中,您可以在每个参数后指定默认值:

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() 方法的理论是,该方法为您提供了在 Route 文件中进行验证的机会。由于您的控制器中已经有了这种可能性,因此不需要它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-18
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    • 2018-10-22
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    相关资源
    最近更新 更多