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

Ligonsker's avatar

How to compare each item in array to its corresponding item in a DB returned collection?

Hello,

I want to validate that the input data is not bigger than the matching max value in the DB.

Assuming the input is a key-value pair where the the key is the id in the DB table, and the value is an array with the value:

[
   22 => ["value" => 100.5],
   103 => ["value" => 85.3],
   221 => ["value" => 20.22]
]

And I get the collection from the DB:

$dataFromDB = MyModel::whereIn('id', array_keys($input))->get();

Returned collection:

[
   ["id" => "22", "max_value" => 150],
   ["id" => "103", "max_value" => 20],
   ["id" => "221", "max_value" => 25]
]

How to check that none of the input values is greater than the max_value column in the table?

Ty

0 likes
3 replies
LaryAI's avatar
Level 58

You can loop through the input array and compare each value with its corresponding max value in the database collection. Here's an example:

$input = [
   22 => ["value" => 100.5],
   103 => ["value" => 85.3],
   221 => ["value" => 20.22]
];

$dataFromDB = MyModel::whereIn('id', array_keys($input))->get();

foreach ($input as $id => $value) {
    $maxValue = $dataFromDB->where('id', $id)->first()->max_value;
    if ($value['value'] > $maxValue) {
        // handle validation error
    }
}

In this example, we loop through each key-value pair in the input array and use the where method to filter the database collection by the corresponding ID. We then use the first method to get the first matching record and access its max_value property. Finally, we compare the input value with the max value and handle any validation errors as needed.

Ligonsker's avatar

That's what I was doing, but does using the collection where takes a lot of resources? Is it slow and can be done in a faster way? Or the collection's where is relatively fast? (In case there are a lot of input values)

Snapey's avatar
Snapey
Best Answer
Level 122

@Ligonsker collections where method is iterating over the collection you have already brought into memory

a slightly quicker way would be to use pluck

$dataFromDB = MyModel::whereIn('id', array_keys($input))->pluck('max_value','id');

then you only get the one value and a key, not a collection of models

you can then access the collection using the key directly rather than where

foreach ($input as $id => $value) {
    if ($value['value'] > $dataFromDB[$id]) {
        // handle validation error
    }
1 like

Please or to participate in this conversation.