Transform dot-noted strings with Laravel's `undot()` method
Laravel devs, here's a gem for you: π
The Laravel Collection class is packed with powerful methods that can simplify your coding tasks. One such feature is the undot()
method, which allows you to transform dot-noted strings back into nested arrays effortlessly. This can be particularly useful when working with complex, hierarchical data structures. Let's explore how to use this method with different real-life examples.
What is undot()
?
The undot()
method converts a collection with dot-noted keys into a nested array. This can be very handy when you need to restructure flat configurations or any other flat data that uses dot notation for nesting.
Real-Life Example 1: Transforming Product Attributes
Imagine you are working on an e-commerce platform, and you have product attributes stored in a flat structure using dot notation. At some point, you may need to convert this flat data back into a nested array to make it easier to manage and display product details.
Example Code
Let's start by creating a collection with product attributes in dot notation:
// Collection of product attributes in dot notation
$productAttributes = collect([
'product.name' => 'Smartphone',
'product.specifications.screen_size' => '6.5 inches',
'product.specifications.battery' => '4000 mAh',
'product.specifications.camera' => '12 MP',
'product.price' => 699.99,
]);
// Convert dot-noted keys to nested array
$product = $productAttributes->undot();
print_r($product->all());
Output
[
"product" => [
"name" => "Smartphone",
"specifications" => [
"screen_size" => "6.5 inches",
"battery" => "4000 mAh",
"camera" => "12 MP"
],
"price" => 699.99
]
]
In this example, we start with a collection containing product attributes where the keys are in dot notation. By applying the undot()
method, we convert this flat structure into a nested array, making it easier to work with the data, especially when you need to display product details in a structured format.
Conclusion
The undot()
method is a powerful addition to the Laravel Collection methods, allowing you to handle and transform data structures efficiently. By leveraging this method, you can ensure that your application processes data in a clean and maintainable way, especially when dealing with hierarchical or nested information.
Found this helpful?
If this guide was helpful to you, subscribe to my daily newsletter and give me a follow on X/Twitter. It helps a lot!
Found this helpful?
If this guide was helpful to you, subscribe to my daily newsletter and give me a follow on X/Twitter. It helps a lot!