Laravel验证数组和缺少参数

时间:2019-06-15 14:37:28

标签: laravel validation laravel-request

我有一个要验证的数组。 json后的有效载荷看起来像这样

{   
    "guid" : "d19b122dc48a4663e33eaa7c83993f7a40ae9329",
    "organization" : {
        "phone" : "0466144569",
        "email" : "test@test.com",
        "country" : "US",
        "language" : "en",
        "name" : "rockstar"
    },
    "user" : {
        "username" : "rockstar",
        "password" : "rockstarpassword",
        "consent" : {
            "gdpr": "true",
            "version": "consent_doc_2009"
        }
    }
}

问题在于,此有效负载可能会在4种不同的情况下发生变化。

1)整个有效负载都存在。就像上面的例子一样。

2)缺少organization的地方。

{   
        "guid" : "d19b122dc48a4663e33eaa7c83993f7a40ae9329",
        "organization" : null
        "user" : {
            "username" : "rockstar",
            "password" : "rockstarpassword",
            "consent" : {
                "gdpr": "true",
                "version": "consent_doc_2009"
            }
        }
    }

3)缺少user的地方。

  { 
        "guid" : "d19b122dc48a4663e33eaa7c83993f7a40ae9329",
        "organization" : {
            "phone" : "0466144569",
            "email" : "test@test.com",
            "country" : "US",
            "language" : "en",
            "name" : "rockstar"
        },
        "user" : null
        }
    }

4)organizationuser都丢失了。

 {  
        "guid" : "d19b122dc48a4663e33eaa7c83993f7a40ae9329",
        "organization" : null,
        "user" : null

    }

我有一个laravel请求类,可以对此进行验证。

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class organizationCreation extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'guid' => 'required|string',
            'organization.name' => 'required_with:organisation|string|min:3',
            'organization.phone' => 'required_with:organisation|regex:/^([0-9\s\-\+\(\)]*)$/|max:20',
            'organization.country' => 'required_with:organisation|max:2',
            'organization.language' => 'required_with:organisation|max:2',
            'organization.email' => 'required_with:organisation|string|max:255',
            'user.username' => 'required_with:user|string|max:255',
            'user.password' => 'required_with:user',
            'user.consent.gdpr' => 'required_with:user|boolean',
            'user.consent.version' => 'required_with:user|string|max:255',
        ];
    }
}

我尝试了上述验证,并使用了required_with,但随后看来验证失败了,而且我不确定如何继续执行具有4条不同规则的验证。

我可以通过用if检查有效负载来单独验证它们,而不是为此编写代码,但是我想一次全部完成。

1 个答案:

答案 0 :(得分:0)

required_with的文档告诉我们以下内容:

  

正在验证的字段必须存在,并且仅当存在其他指定字段时才为空。

在您的情况下,该字段存在,但它们具有null值。是否可以完全不发送密钥,或者您是否无法控制使用API​​的客户端?在这种情况下,您可以使用中间件代替空值。

相关问题