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

it-is-all-about-laravel's avatar

Rule::exists Validation of Array

Hey Everyone, I have a requirement to validate a request attribute array contains values that exist in a database table. The submitted array is an array of objects, i can use the id attribute of each object to check that id exists on my database tabel. I think Rule::exists might be suitable to meet the requirement, but I'm unclear how to get access to the submitted values in the array to validate them. What I have so far is below, can you recommend how this requirement can be best solved?

// excerpt of validation rules
 'cities' => 'required|array',
 'cities.*' => [
       Rule::exists('cities')->where(function ($query) {
        // i woulld like something like 
        $query->where('id', $array_item->id)
       // but i can't find how i access the array_item
        }),
      ],
0 likes
7 replies
it-is-all-about-laravel's avatar

Each element in the array I receive on the request is an object, one attribute of which is the id. eg

['id' => 1, 'city' => 'Paris'],
['id' => 2, 'city' => 'Dubai'],
]

How do you recommend getting access to the id attribute and comparing it to the id column in my cities table?

jove's avatar
jove
Best Answer
Level 7
'cities' => 'required|array',
'cities.*.id' => 'exists:cities,id'
2 likes
DmitryVasylchuk's avatar

Hey, maybe anyone know. If I have a huge array and I know that rule "exists" use database query like COUNT(*). So I wonder how many will be queries for DB. Is laravel so smart to do it "where in" way or I will have as many queries as I have array items. Thank you!

Please or to participate in this conversation.