mercredi 26 avril 2017

Laravel 5 - validate array as required, but allow an empty array to be passed

I'm validating a request in Laravel 5.4 with the validator, see the documentation: http://ift.tt/2lWKnbI

Basically, it's this code:

public function createSomeresource(Request $request)
{
    $this->validate($request, [
        'items' => 'required',
    ];
    ...
}

I would like to require the presence of the field "items" and this code does it, but the problem is that the validation fails when the "items" field is an empty array, i.e.

{
    "fields": []
}

, which is an undesired behavior. I know that's the documented behavior of the "required" parameter but I don't see any "clean" workaround. I tried also:

public function createSomeresource(Request $request)
{
    $this->validate($request, [
        'items' => 'required_unless:items,[]',
    ];
    ...
}

but it fails as well, probably because the documentation says that it works with a different field after the "required_unless" clause, but I'm not totally sure about it.

Could you suggest me a way to require the presence of the field "items" without forbidding the empty array?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2pl7RwA
via IFTTT

Aucun commentaire:

Enregistrer un commentaire