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

fredsted's avatar

Validating an array of objects

Hello,

I'm making a REST endpoint which sends email, and for each recipient there needs to be both an email and a name. The way I want to do that is this:

{
  "recipients": [
    {
      "email": "user@example.com"
      "name": "Jonathan Doe"
    },
    {
      "email": "mike@hotmail.ninja"
      "name": "Mike Jameson"
    }
  ]
}

But how do I validate this? Making sure the recipients field is an array is easy, but I can't quire figure out how to make sure each of the array items is an object containing these two fields.

(I've looked a bit at the previous threads, and found something Laravel specific, but I had a hard time adapting that to my Lumen project, since Lumen doesn't really support custom Request objects that hook into the validator, or I haven't figured it out, anyway)

Any ideas?

0 likes
4 replies
toniperic's avatar

Use array_filter.

$validItems = array_filter($recipients, function($item){
    return isset($item['email'], $item['name']); // true or false
});

array_filter iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array.

Not really sure what the context is though. If you're using Laravel, you can as well use Collection's filter method.

Hope this helps.

fredsted's avatar

Thanks for the response, maybe I should post some of the code I've been messing with in my Lumen project.

This would kind of do what I want, except it only validates the first object of the array:

        $this->validate($request, [
            'to' => 'required|array',
            'to.0.email' => 'required|email',
            'to.0.name' => 'required|string',
        ]);

If I wanted to validate all, I'd have to something like:

$validation = [];
for ($i = 1; $i <= count($request->get('recipients')); $i++) {
    $validation[] = [
            'to.'.$i.'.email' => 'required|email',
            'to.'.$i.'.name' => 'required|string',
    ];
}

$this->validate($request, ['to' => 'required|array'] + $validation);

(note: above code not tested)

But having to generate validation rules like that seems counterintuitive to the benefits Lumen's validator provides, and I'd very much like to avoid doing it like that..

toniperic's avatar

Think you can use the following (or maybe it's L5.2, not sure)

$this->validate($request, [
    'to' => 'required|array',
    'to.*.email' => 'required|email',
    'to.*.name' => 'required|string',
]);
3 likes
fredsted's avatar

Thanks – looks like it's a 5.2 feature:

{
  "errors": {
    "to.*.email": [
      "The to.*.email field is required."
    ],
    "to.*.name": [
      "The to.*.name field is required."
    ]
  }
}

Please or to participate in this conversation.