Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

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();
Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

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.

Comments?