Laravel Tutorials

Deep Array Manipulation with Laravel's replaceRecursive Method

Published Updated
Deep Array Manipulation with Laravel's replaceRecursive Method image

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 App\Services;
use Illuminate\Support\Collection;
 
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.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Laravel AI SDK 1.0 Adds Classification and Tool Approvals image

Laravel AI SDK 1.0 Adds Classification and Tool Approvals

Read article
Tagged Memoized Cache and Model Refreshes in Laravel 13.33 image

Tagged Memoized Cache and Model Refreshes in Laravel 13.33

Read article
Laravel Live Denmark 2026 Talks Are Now on YouTube image

Laravel Live Denmark 2026 Talks Are Now on YouTube

Read article
Live Stream: Building a Social Network in PHP in 48 Hours image

Live Stream: Building a Social Network in PHP in 48 Hours

Read article
Health for Laravel: Kubernetes Probes and Prometheus Metrics image

Health for Laravel: Kubernetes Probes and Prometheus Metrics

Read article
Fast Excel 5.x Adds Streaming Imports and Safer Exports image

Fast Excel 5.x Adds Streaming Imports and Safer Exports

Read article