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

masteringlaravel logo
Laravel Code Review

Get expert guidance in a few days with a Laravel code review

Visit Laravel Code Review

The latest

View all →
Validate and Convert HEIC Images in Laravel image

Validate and Convert HEIC Images in Laravel

Read article
Saga Lara Flow: Durable Workflows and Compensating Transactions on Laravel Queues image

Saga Lara Flow: Durable Workflows and Compensating Transactions on Laravel Queues

Read article
Reject Unexpected Array Keys with Laravel Validation image

Reject Unexpected Array Keys with Laravel Validation

Read article
Major performance improvements & security patches for Filament v4.12 and v5.7! image

Major performance improvements & security patches for Filament v4.12 and v5.7!

Read article
Laravel Boost Project Rules: Teach Agents Your Conventions image

Laravel Boost Project Rules: Teach Agents Your Conventions

Read article
Extract an Image's Dominant Color in Laravel image

Extract an Image's Dominant Color in Laravel

Read article