【问题标题】:Validate JS Array request in Laravel Controller在 Laravel 控制器中验证 JS 数组请求
【发布时间】:2019-02-25 01:32:36
【问题描述】:

我只想确保来自 JS 端的数据是一个数组。所以从the accepted answer 可以看出,在验证中写'array' 就足够了。但就我而言,当我写作时:

$request->validate([
    'tags' => 'array',
]);

并使用Postman 传递一个数组[1,2,3],我得到一个错误["The tags must be an array."],并且php 将它作为一个字符串处理,所以当我尝试获取例如第一个元素$request->tags[0] 时,我收到'['。这里有什么问题?

【问题讨论】:

    标签: php arrays laravel validation controller


    【解决方案1】:

    当你传递[1,2,3] 时,它看起来好像不是一个数组,它实际上只是一个字符串。当您在 PHP 中将字符串视为数组时,它会为您提供该字符,因此 $request->tags[0] 只是为您提供字符串中的第一个字符 [

    使用 postman 并添加键值对时,请像这样设置键和值...

    +--------+-------+
    | Key    | Value |
    +--------+-------+
    | tags[] | 1     |
    | tags[] | 2     |
    | tags[] | 3     |
    +--------+-------+
    

    【讨论】:

    • 这是 Postman 特有的问题,还是我也必须在真正的 JS 中做类似的事情?
    • 我不会称之为邮递员问题。这正是 PHP 在使用数组时期望查询字符串被格式化的方式。 ex test.php?tags=[1,2,3] PHP 会将标签确定为字符串。 test.php?tags[]=1&tags[]=2&tags[]=3 PHP 将确定为一个数组。如果您使用 JS,则取决于您的操作方式,很有可能会为您处理。
    【解决方案2】:
    <form ..>
      <input name="tags[]" value="1">
      <input name="tags[]" value="2">
      <input name="tags[]" value="2">
    </form>
    
    <script>
     //your code to serialise and post form through JS goes here
    </script>
    

    在您的请求类中

    //TagsRequest.php
    public function rules(){
      return [
        'tags'=>['array'],
        'tags.*'=>[
           //add rules for tags array elements
        ]
      ]
    
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-26
      • 1970-01-01
      • 2021-02-15
      • 2016-10-24
      • 2019-12-29
      • 2016-08-10
      • 2020-09-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多