Laravel 5 - check array as needed, but allow empty array passing

I am validating a request in Laravel 5.4 with a validator, see documentation: https://laravel.com/docs/5.4/validation#validating-arrays

Basically, this code in the controller:

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

      

I would like to require the "items" fields and this code does so, but the problem is that the check fails when the "items" field is an empty array, i.e.

{
    "fields": []
}

      

which is undesirable behavior. I know the documented behavior of a "required" parameter, but I don't see a "clean" workaround. I also tried:

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

      

but it doesn't work either, perhaps because the documentation says it works with a different field after the "required_unless" clause, but I'm not entirely sure about that.

Could you please suggest me a way to require "items" fields without disallowing an empty array?

EDIT: Another "obvious" approach that came to my mind is to use the "real array" rule and it almost does what I want, but unfortunately the empty string also conveys this validation rule, which is perhaps , a bug in Laravel, maybe not - I opened an issue for it in the Laravel github repository: https://github.com/laravel/framework/issues/18948

+3


source to share


4 answers


Try the following:



public function createSomeResource(Request $request)
{
    $this->validate($request, [
        'items' => 'present|array',
    ];
    ...
}

      

+11


source


Here we go buddy ...



public function createSomeResource(Request $request)
{
    $validate_us_pls = [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ];


    if( !empty($request->get('items')) ){
        $validate_us_pls['items'] = 'required';
    }

    $this->validate($request, $validate_us_pls);

}

      

+2


source


Try:

public function createSomeResource(Request $request)
{
    $this->validate($request, [
        'items' => 'required|array|min:1',
    ];
    ...
}

      

From the Laravel doc:

min: value The field under validation must have a minimum value. Strings, numbers, arrays and files are evaluated in the same way as the size rule.

+2


source


Maybe this will be helpful?

the size of the array uses count

 'ids'=>'present|array|size:1'

      

or

'users' => 'required|array|between:2,4'

      

0


source







All Articles