In this article, we will explore three essential helpers: "data_set," "data_get," and "data_fill". These helpers are powerful tools which help with data manupulation.
Its purpose is simple yet powerful: setting values within nested arrays or objects using "dot notation." Let's take a look at a practical example:
$data = [];
data_set($data, 'user.name', 'John Doe');
With just a few lines of code, we create an empty array $data and utilize the "data_set" helper to set the value "John Doe" at the nested key "user.name". Laravel takes care of creating intermediate arrays or objects automatically, ensuring your desired value is correctly placed.
The "data_get" helper in Laravel allows for seamless retrieval of values from nested arrays or objects using "dot notation." Let's see it in action:
$data = [
'user' => [
'name' => 'John Doe',
'email' => '[email protected]',
],
];
$name = data_get($data, 'user.name');
In this example, we have an array $data, and by utilizing the "data_get" helper, we can effortlessly retrieve the value of "user.name" (i.e., 'John Doe'). This helper method traverses the nested structure, enabling easy access to deeply nested values.
The "data_fill" helper in Laravel allows for easy filling of nested arrays or objects with a given value. Unlike "data_set," it only sets the value if the key does not already exist. Let's see it in action:
$data = [
'user' => [
'name' => 'John Doe',
],
];
data_fill($data, 'user.email', '[email protected]');
In this example, the array $data already contains the "user" key with a "name" value. By using the "data_fill" helper, we fill the nested key "user.email" with the value "[email protected]". However, if the key already exists, the helper method will not modify the value.
The true strength of these helpers lies in their ability to work together, simplifying complex data manipulations. Let's consider a scenario where we want to retrieve a nested value while providing a default value if it doesn't exist. This can be achieved by combining "data_get" and "data_fill":
$data = [
'user' => [
'name' => 'John Doe',
],
];
$email = data_get($data, 'user.email', '[email protected]');
In this example, the "data_get" helper attempts to retrieve the value of "user.email" from $data. If the key doesn't exist, it returns the default value "[email protected]"