What is the Fluent Class?
TheFluent class is a versatile utility class that allows you to work with arrays as if they were objects. Implemented in Illuminate\Support\Fluent, it has existed since Laravel’s early versions but is rarely documented in the official guides.
Internally, it manages array data as properties and uses magic methods (__get, __set, __call) to provide property-like read/write access.
Creating Instances
Constructor
make() Factory Method
fluent() Helper Function
Laravel 11 introduces thefluent() helper function, equivalent to Fluent::make().
Property Access
Dynamic Property Read/Write
Method Chaining
The__call magic method allows you to call non-existent methods to set properties. Each method returns $this, enabling chaining.
Key Methods
get() — Access Using Dot Notation
set() — Set Values Using Dot Notation
fill() — Set Multiple Properties at Once
all() — Get All Properties as Array
scope() — Convert Nested Values to New Fluent Instance
value() — Set Default Values Using Callbacks
Array Operations
toArray() — Convert to Array
getAttributes() — Direct Access to Internal Attributes
ArrayAccess Interface
Fluent implementsArrayAccess, allowing array-like operations.
IteratorAggregate Interface
Fluent can be looped using foreach.JSON Processing
toJson() — Convert to JSON String
toPrettyJson() — Convert to Formatted JSON
JsonSerializable Interface
Fluent implementsJsonSerializable, allowing direct use with json_encode().
State Checking
isEmpty() / isNotEmpty()
Conditionable Trait
Fluent uses theConditionable trait, supporting conditional operations.
when() / unless() methods enables fluent configuration based on conditions.
Macroable Trait
Fluent also uses theMacroable trait, allowing dynamic method addition.
Practical Use Cases
API Response Builder
Configuration Builder
Request Parameter Validation and Transformation
Model and Fluent Integration
Form Data Normalization
Comparison with Other Classes
Fluent vs Array
Fluent vs Model
Internal Implementation Details
__call method, when no macro is registered, sets the method name as the property key with the provided value and returns $this, enabling method chaining.
Next Steps
Collection Class
Deep dive into the Collection class for working with multiple elements.
Conditionable Trait
Learn to write conditional logic fluently with the Conditionable trait.
Macroable Trait
Learn to dynamically add methods to existing classes with the Macroable trait.