Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

gianmarx's avatar

Validate an array as an optional parameter in API

I created a request for an API. this API can have an array as an optional parameter. unfortunately when I send him the following parameter:

{
    "field_a" : null
}

e.g: I pass the array in json format

unfortunately it manages to pass the Request. The request in question is the following:

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class BungaBungaRequest extends Request
{

    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            field_a => 'nullable|array|min:1',
            field_a.* => 'required|string|in:picasso,obama'
        ];
    }
}

in the Request I am telling him that the array can be optional as a parameter, but if there is it cannot be empty only if I send it declared to NULL. pass the Request.

0 likes
4 replies
Tjyoung's avatar
Tjyoung
Best Answer
Level 14

You can create a custom rule using,

php artisan make:rule CustomArrayRule

and define your own rule like following,

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class CustomArrayRule implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
         if($value === null){
             return true;
         }
		 // check if input is not array and if array then length shouldn't less than one														
         return (gettype($value) <> 'array' || count($value) < 1) ? false : true;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must contain at least one array element.';
    }
}

then use it in your code,

$validated = request()->validate([
        'field' => [new \App\Rules\CustomArrayRule()],
    ]);
1 like
gianmarx's avatar

@Tjyoung thanks a lot i made a little fix great idea

  public function passes($attribute, $value)
    {
         if($value === null){
             return false;
         }
		 // check if input is not array and if array then length shouldn't less than one														
         return (gettype($value) <> 'array' || count($value) < 1) ? false : true;
    }

Please or to participate in this conversation.