The fluent data helper in Laravel
When working with Laravel, you might need to manipulate data in various ways. For instance, when your data is a multi-dimensional array, you might need to filter, sort, or map the data to get the desired result.
Let’s say you have the following multi-dimensional array.
$data = [
'user' => [
'name' => 'Amit',
'address' => [
'city' => 'Surat',
'state' => 'Gujarat',
]
],
];
The good ol’ collect
helper
We can use the collect
helper to convert this array into a collection and then use the data
method to manipulate the data.
Here’s how you can get the user’s name from the above array using the collect
helper.
$filteredData = collect($data)->data('user')['name'];
// Output: Amit
Or, you can get the user’s city using the same method.
$filteredData = collect(collect($data)->data('user'))->pluck('address')['city'];
While this will get the job done, it’s not very readable.
That’s where this fluent helper shared by Philo Hermans comes in.
The fluent data helper
Philo Hermans shared a fluent data helper that allows you to manipulate multi-dimensional arrays in a more readable way.
This helper is now part of the Laravel core as of Laravel 11.2.0.
Here’s how the helper looks.
if (! function_exists('fluent')) {
function fluent($data): \Illuminate\Support\Fluent
{
return new \Illuminate\Support\Fluent($data);
}
}
As you can tell, the helper uses Laravel’s lesser-known Illuminate\Support\Fluent
class under the hood to manipulate the data.
So, you can use this helper to manipulate the data like so.
$filteredData = fluent($data)->get('user.name');
// Output: Amit
Or, you can get the user’s city using the same method.
$filteredData = fluent($data)->get('user.address.city');
You can even use methods like toJSON
fluently.
$jsonData = fluent($data)->get('user.address')->toJSON();
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.