Laravel provides several powerful helpers for working with arrays. While Arr::dot()
helps flatten nested arrays into a dot-notated format, Laravel 10 introduced its counterpart: Arr::undot()
. This handy method reverses the process by transforming a flattened array back into its original nested structure.
In this article, we’ll explore how Arr::undot()
works, when you might use it, and how it complements Arr::dot()
in real-world Laravel applications.
What is Arr::undot()
?
Arr::undot()
takes an array with keys in dot notation and reconstructs it into a multidimensional (nested) array.
Syntax
Arr::undot(array $array): array
-
$array: An array with keys using dot notation (e.g.,
user.name
,user.address.city
).
Example
Flattened Array (Input)
use Illuminate\Support\Arr;
$data = [
'user.name' => 'John',
'user.address.city' => 'New York',
'user.address.zip' => '10001',
];
Applying Arr::undot()
$nested = Arr::undot($data);
print_r($nested);
Output
[
'user' => [
'name' => 'John',
'address' => [
'city' => 'New York',
'zip' => '10001',
],
],
]
As shown, the method intelligently parses each dot-notated key and builds a properly nested structure.
Common Use Cases
1. Reversing Arr::dot()
This is the most obvious use. If you've previously flattened a structure for processing or storage, Arr::undot()
helps you restore it.
2. Data Normalization
When storing flat key-value pairs (like settings or metadata), you might later want to convert them back into a usable nested structure.
3. Dynamic Form Building
In cases where form data is stored in dot-notated keys (e.g., form.field.name
), this function helps structure the data for rendering grouped UI elements.
Combined Usage Example
use Illuminate\Support\Arr;
$original = [
'profile' => [
'name' => 'Alice',
'social' => [
'twitter' => '@alice',
'github' => 'alicehub',
],
],
];
$flattened = Arr::dot($original);
$rebuilt = Arr::undot($flattened);
dd($rebuilt);
The $rebuilt
array will exactly match the $original
, proving how these methods can be used together for transformation and restoration.
The Arr::undot()
method is a simple yet powerful addition to Laravel’s robust array handling features. It’s especially useful when dealing with configuration, translation, and form data that benefit from both flattened and nested representations.
Understanding how and when to use Arr::undot()
(in combination with Arr::dot()
) can lead to cleaner, more maintainable code and efficient data manipulation workflows.
0 Comments