Laravel’s replaceRecursive method offers a powerful solution for updating nested arrays while preserving unmodified values, particularly useful when working with complex configuration structures.
$collection = collect([
'user' => [
'name' => 'John',
'settings' => [
'theme' => 'dark',
'notifications' => true,
]
]
]);
$updated = $collection->replaceRecursive([
'user' => [
'settings' => [
'theme' => 'light'
]
]
]);
Let’s explore a practical example with a configurable dashboard system:
<?php
namespace AppServices;
use IlluminateSupportCollection;
class DashboardConfigurationService
{
public function mergeUserPreferences(array $defaultConfig, array $userPreferences): array
{
return collect($defaultConfig)->replaceRecursive($userPreferences)->all();
}
public function getConfiguration(User $user): array
{
$defaultConfig = [
'layout' => [
'sidebar' => [
'position' => 'left',
'width' => 250,
'collapsed' => false
],
'theme' => [
'mode' => 'light',
'color' => 'blue',
'font_size' => 14
],
'widgets' => [
'weather' => true,
'calendar' => true,
'notifications' => true
]
]
];
return $this->mergeUserPreferences(
$defaultConfig,
$user->dashboard_preferences ?? []
);
}
}
ReplaceRecursive provides an elegant way to handle deep array updates while maintaining unspecified values, perfect for managing configuration merges and preference systems.
The post Deep Array Manipulation with Laravel’s replaceRecursive Method appeared first on Laravel News.
Join the Laravel Newsletter to get all the latest
Laravel articles like this directly in your inbox.
Source: Read MoreÂ