Laravel Tutorials

Handle Nested Arrays Elegantly with Laravel's fluent() Helper

Published
Handle Nested Arrays Elegantly with Laravel's fluent() Helper image

Laravel introduces the fluent() helper function for smoother multi-dimensional array handling, providing an intuitive approach to access and manipulate nested data structures.

Work with multi-dimensional arrays using the fluent helper:

$config = [
'app' => [
'name' => 'TaskManager',
'settings' => [
'timezone' => 'UTC',
'locale' => 'en',
]
],
'features' => [
['name' => 'Analytics'],
['name' => 'Reports']
]
];
 
fluent($config)->app;
fluent($config)->get('app.name');
fluent($config)->collect('features')->pluck('name');
fluent($config)->scope('app.settings')->toJson();

Here's a practical implementation for an API response builder:

class ApiResponseBuilder extends Controller
{
public function buildResponse(Product $product)
{
$responseData = [
'product' => [
'details' => [
'title' => $product->title,
'price' => $product->price,
'created' => $product->created_at
],
'options' => [
'variants' => $product->variant_settings,
'shipping' => $product->shipping_options
]
],
'metrics' => [
'views' => $product->views->count(),
'orders' => $product->orders->count(),
'reviews' => $product->reviews->count()
]
];
 
$response = fluent($responseData);
 
return response()->json([
'title' => $response->get('product.details.title'),
'price' => $response->get('product.details.price'),
'shipping' => $response->get('product.options.shipping'),
'analytics' => $response->scope('metrics')->toArray(),
'variants' => $response
->collect('product.options.variants')
->filter(fn($available) => $available)
->keys()
]);
}
}

The fluent helper makes complex array operations more readable and maintainable.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

acquaintsoft logo
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech

The latest

View all →
Cancel In-Flight Form Submissions in Inertia.js v3.7 image

Cancel In-Flight Form Submissions in Inertia.js v3.7

Read article
Laravel Starter Kits Now Ship with Vite+ image

Laravel Starter Kits Now Ship with Vite+

Read article
Pessimistic Locking in Laravel Eloquent with refreshForUpdate() image

Pessimistic Locking in Laravel Eloquent with refreshForUpdate()

Read article
Mask Query Bindings in Laravel Exception Messages image

Mask Query Bindings in Laravel Exception Messages

Read article
whereBinary(): Case-Sensitive MySQL Queries in Laravel image

whereBinary(): Case-Sensitive MySQL Queries in Laravel

Read article
Compile PHP to Native Binaries with TypePHP image

Compile PHP to Native Binaries with TypePHP

Read article