Laravel Tutorials

Handle Fluent Values as Arrays with Laravel's array() Method

Published
Handle Fluent Values as Arrays with Laravel's array() Method image

Laravel simplifies Fluent object value handling with the introduction of the array() method, providing a clean approach to convert values into arrays without manual casting or collection manipulation.

Working with Fluent objects often requires ensuring values are returned as arrays, especially when dealing with configuration data or dynamic properties. Previously, this involved manual casting or collection methods. The new array() method streamlines this process:

$fluent = new Fluent(['email' => 'admin@example.com']);
$emails = $fluent->array('email');
// Result: ['admin@example.com']

This method proves particularly valuable in settings management systems:

class SettingsManager
{
protected $settings;
 
public function __construct(array $config)
{
$this->settings = new Fluent($config);
}
 
public function getNotificationChannels(string $event)
{
// Always get channels as array
return $this->settings->array("alerts.{$event}.channels");
}
 
public function getTrustedHosts()
{
// Previously: (array) $this->settings->get('hosts')
// Or: $this->settings->collect('hosts')->all()
return $this->settings->array('trusted_hosts');
}
 
public function getBackupLocations()
{
// Single location or multiple will always return array
return $this->settings->array('backup_locations');
}
}

The array() method eliminates conditional checks and type casting, creating cleaner, more maintainable code when working with Fluent instances that need consistent array output.

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 →
PayZephyr: One Payment API for Stripe, Paystack, and PayPal image

PayZephyr: One Payment API for Stripe, Paystack, and PayPal

Read article
Bifrost Turns One With AI Builds and New Workflows image

Bifrost Turns One With AI Builds and New Workflows

Read article
Preview Blade Templates in macOS Finder with Quick Blade image

Preview Blade Templates in macOS Finder with Quick Blade

Read article
Artisan Debugging Commands in Laravel Telescope 5.24.0 image

Artisan Debugging Commands in Laravel Telescope 5.24.0

Read article
Queue totalSize() and JobInterrupted Event in Laravel 13.31 image

Queue totalSize() and JobInterrupted Event in Laravel 13.31

Read article
Find Unexpected Test Inputs with Fuzz for Pest image

Find Unexpected Test Inputs with Fuzz for Pest

Read article