Converting Fluent Values to Arrays in Laravel

Converting Fluent Values to Arrays in Laravel

Need to consistently handle values as arrays in your Fluent instances? Laravel's new array() method provides a clean way to convert values without manual casting.

When working with Fluent objects, you often need to ensure values are returned as arrays. Previously, this required manual casting or collection manipulation. The new array() method simplifies this process by providing a direct way to get array values from your Fluent instances.

Let's see how it works:

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

Real-World Example

Here's how you might use it in a configuration manager:

class ConfigurationManager
{
    protected $config;

    public function __construct(array $settings)
    {
        $this->config = new Fluent($settings);
    }

    public function getEmailRecipients(string $type)
    {
        // Always get recipients as array
        return $this->config->array("notifications.{$type}.recipients");
    }

    public function getAllowedDomains()
    {
        // Previously: (array) $this->config->get('domains')
        // Or: $this->config->collect('domains')->all()
        return $this->config->array('domains');
    }

    public function getAdminUsers()
    {
        // Single admin or multiple will always return array
        return $this->config->array('admin_users');
    }
}

The array() method simplifies value handling in your Fluent instances by ensuring consistent array output. This eliminates the need for manual type casting or collection methods, making your code cleaner and more maintainable.

Think of it as an automatic array normalizer for your Fluent objects - whether your property contains a single value or multiple values, you'll always get an array back. This becomes especially valuable when:

  • Handling configuration values that might be single or multiple
  • Processing user settings
  • Managing lists of values
  • Working with dynamic properties

For example, instead of checking if a value is an array or using collection methods, you can simply use the array() method and know you'll get a consistent result.

If this guide was helpful to you, subscribe to my daily newsletter and give me a follow on X/Twitter and Bluesky. It helps a lot!

Subscribe to Harris Raftopoulos

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe