Key-Based Collection Comparison with Laravel's diffKeys Method
Laravel's collection system includes the powerful diffKeys method, helping you identify differences between collections based on their keys rather than values.
Basic Usage
Compare collections by their keys:
$collection = collect([
'one' => 10,
'two' => 20,
'three' => 30,
'four' => 40,
'five' => 50,
]);
$diff = $collection->diffKeys([
'two' => 2,
'four' => 4,
'six' => 6,
]);
// Result: ['one' => 10, 'three' => 30, 'five' => 50]
Real-World Example
Here's how you might use it in a configuration manager:
class ConfigurationManager
{
public function findRemovedSettings(array $oldConfig, array $newConfig)
{
return collect($oldConfig)
->diffKeys($newConfig)
->map(function ($value, $key) {
return [
'key' => $key,
'old_value' => $value,
'removed_at' => now()
];
});
}
public function validateRequiredKeys(array $config)
{
$required = [
'database' => null,
'cache' => null,
'queue' => null
];
$missing = collect($required)
->diffKeys($config)
->keys();
if ($missing->isNotEmpty()) {
throw new InvalidConfigurationException(
'Missing required configuration keys: ' .
$missing->implode(', ')
);
}
return true;
}
public function syncConfigurations(array $source, array $target)
{
$added = collect($source)->diffKeys($target);
$removed = collect($target)->diffKeys($source);
return [
'added' => $added->all(),
'removed' => $removed->all(),
'changes' => $added->count() + $removed->count()
];
}
}
The diffKeys method makes it easy to track changes and validate configurations based on their keys.
If this guide was helpful to you, subscribe to my daily newsletter and give me a follow on X/Twitter and Bluesky. It helps a lot!