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

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article