Use dot() to flatten nested multi-dimensional arrays into single-level dot notation maps, and undot() to reconstruct full nested structures.
When storing nested configuration dictionaries in database key-value stores or converting JSON payloads for form inputs, manipulating nested arrays is complex.
Laravel Collections provide dot() and undot().
Flattening with dot()
$settings = collect([
'app' => [
'theme' => 'dark',
'notifications' => [
'email' => true,
'sms' => false,
]
]
]);
$flattened = $settings->dot();
// Output:
// [
// 'app.theme' => 'dark',
// 'app.notifications.email' => true,
// 'app.notifications.sms' => false,
// ]
Reconstructing Nested Structures with undot()
$dotArray = collect([
'user.name' => 'Punyapal',
'user.contact.email' => '[email protected]',
]);
$nested = $dotArray->undot();
// Output:
// [
// 'user' => [
// 'name' => 'Punyapal',
// 'contact' => [
// 'email' => '[email protected]'
// ]
// ]
// ]
Summary
dot()flattens multi-level hierarchies into dot-notated single-level arrays.undot()expands dot-notated keys back into multidimensional structures.- Essential for config caches and dynamic settings forms.
Tags:
Laravel Collections Arrays Data Transformation