Working with nested data structures just got easier with Laravel's Fluent class and its set() method. This feature provides a more intuitive approach to managing complex, nested attributes in your applications. Instead of dealing with cumbersome array initialization and access, you can leverage dot notation to create and interact with multi-level structures seamlessly.
$fluent = new Fluent; // Basic attributes$fluent->set('product', 'iPhone') ->set('version', 15); // Nested attributes$fluent->set('specs.color', 'Space Black') ->set('specs.price.usd', 1199); // Access valuesecho $fluent->product; // "iPhone"echo $fluent->get('specs.color'); // "Space Black"echo $fluent->specs['price']['usd']; // 1199
The dot notation makes it especially convenient to work with multi-level data structures without having to create each level explicitly.
class ProductConfigurator{ private $config; public function __construct() { $this->config = new Fluent; } public function setBasicDetails(string $name, string $sku) { $this->config ->set('product.name', $name) ->set('product.sku', $sku) ->set('product.created_at', now()); return $this; } public function setPricing(float $base, array $taxes) { $this->config ->set('pricing.base', $base) ->set('pricing.taxes', $taxes) ->set('pricing.total', $base + array_sum($taxes)); return $this; } public function setShipping(array $dimensions, float $weight) { $this->config ->set('shipping.dimensions', $dimensions) ->set('shipping.weight', $weight) ->set('shipping.requires_special', $weight > 20); return $this; } public function getConfiguration() { return $this->config; }} $configurator = new ProductConfigurator();$product = $configurator ->setBasicDetails('Gaming Laptop', 'LAP-2024-001') ->setPricing(999.99, ['vat' => 199.99]) ->setShipping(['length' => 15, 'width' => 10], 2.5) ->getConfiguration();
With the Fluent set() method, you can create elegant configuration systems that maintain readability even as complexity increases. This approach eliminates the need for nested array initialization and provides a clean interface for managing related data.