> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Fluent-klasse

> Hoe je met de klasse Illuminate\Support\Fluent arraydata als een object behandelt. Een verborgen maar handige klasse die al sinds de vroege dagen van Laravel bestaat.

## Wat is de Fluent-klasse?

De `Fluent`-klasse is een generieke utilityklasse waarmee je een array als een object kunt behandelen. De klasse is geïmplementeerd in `Illuminate\Support\Fluent` en bestaat al sinds vroege versies van Laravel, maar wordt in de officiële documentatie nauwelijks genoemd.

Intern beheert de klasse de array als property en realiseert die via magic methods (`__get` / `__set` / `__call`) het lezen en schrijven alsof het properties zijn.

<Tip>
  In Laravel 11 is de `fluent()`-helper toegevoegd en is de Fluent-klasse functioneel versterkt — juist nu een uitstekende klasse om te benutten.
</Tip>

## Een instantie maken

### Constructor

```php theme={null}
use Illuminate\Support\Fluent;

// Initialiseren met een array
$user = new Fluent(['name' => 'Laravel', 'type' => 'Framework']);

echo $user->name; // 'Laravel'
echo $user->type; // 'Framework'
```

### De factorymethode make()

```php theme={null}
use Illuminate\Support\Fluent;

$config = Fluent::make([
    'host' => 'localhost',
    'port' => 3306,
    'database' => 'laravel'
]);

echo $config->host; // 'localhost'
```

### De helperfunctie fluent()

In Laravel 11 is de `fluent()`-helper toegevoegd. Deze is gelijk aan `Fluent::make()`.

```php theme={null}
$request = fluent([
    'method' => 'POST',
    'path' => '/api/users',
    'status' => 201
]);

echo $request->method; // 'POST'
```

## Toegang tot properties

### Dynamische properties lezen en schrijven

```php theme={null}
$fluent = new Fluent();

// Schrijven
$fluent->name = 'Laravel';
$fluent->version = 13;

// Lezen
echo $fluent->name;    // 'Laravel'
echo $fluent->version; // 13
```

### Method chaining

Dankzij de magic method `__call` wordt bij het aanroepen van een niet-bestaande methode een property gezet. De methode geeft `$this` terug, dus je kunt chainen.

```php theme={null}
$config = new Fluent();

$config
    ->host('localhost')
    ->port(3306)
    ->database('laravel')
    ->username('root')
    ->password('secret');

echo $config->host;     // 'localhost'
echo $config->password; // 'secret'
```

Met dit mechanisme kun je waarden instellen via een vloeiende API (fluent interface) in plaats van een array.

## Belangrijkste methodes

### get() — toegang via puntnotatie

```php theme={null}
$user = new Fluent([
    'profile' => [
        'email' => 'user@example.com',
        'phone' => '090-xxxx-xxxx'
    ]
]);

// Geneste waarden ophalen met puntnotatie
$email = $user->get('profile.email'); // 'user@example.com'
$phone = $user->get('profile.phone'); // '090-xxxx-xxxx'

// Een standaardwaarde opgeven kan ook
$fax = $user->get('profile.fax', 'N/A'); // 'N/A'
```

### set() — zetten via puntnotatie

```php theme={null}
$fluent = new Fluent();

$fluent->set('user.name', 'Laravel');
$fluent->set('user.email', 'laravel@example.com');

print_r($fluent->toArray());
// Array (
//     [user] => Array (
//         [name] => Laravel
//         [email] => laravel@example.com
//     )
// )
```

### fill() — meerdere properties in één keer zetten

```php theme={null}
$fluent = new Fluent(['initial' => 'value']);

$fluent->fill([
    'name' => 'Laravel',
    'version' => 13,
    'license' => 'MIT'
]);

echo $fluent->name;    // 'Laravel'
echo $fluent->version; // 13
```

### all() — alle properties als array ophalen

```php theme={null}
$fluent = fluent([
    'name' => 'Laravel',
    'version' => 13,
    'license' => 'MIT'
]);

// Alle properties
$all = $fluent->all();
// ['name' => 'Laravel', 'version' => 13, 'license' => 'MIT']

// Alleen bepaalde properties
$subset = $fluent->all(['name', 'license']);
// ['name' => 'Laravel', 'license' => 'MIT']
```

### scope() — geneste waarden omzetten naar een nieuwe Fluent

```php theme={null}
$config = fluent([
    'database' => [
        'host' => 'localhost',
        'port' => 3306,
        'name' => 'laravel'
    ]
]);

$dbConfig = $config->scope('database');
// $dbConfig is een nieuwe Fluent-instantie

echo $dbConfig->host; // 'localhost'
echo $dbConfig->port; // 3306
```

Zo kun je een geneste array behandelen als een apart Fluent-object.

### value() — standaardwaarde dynamisch opgeven via een callback

```php theme={null}
$user = fluent(['role' => 'admin']);

// Bestaat de sleutel, dan wordt de waarde teruggegeven
$role = $user->value('role'); // 'admin'

// Bestaat de sleutel niet, dan wordt de standaardwaarde teruggegeven
$status = $user->value('status', 'active');
// 'active'

// De standaardwaarde als callback opgeven
$timestamp = $user->value('updated_at', function () {
    return now()->toIso8601String();
});
```

## Arraybewerkingen

### toArray() — omzetten naar een array

```php theme={null}
$fluent = fluent(['name' => 'Laravel', 'version' => 13]);

$array = $fluent->toArray();
// ['name' => 'Laravel', 'version' => 13]

print_r($array);
```

### getAttributes() — directe toegang tot de interne attributen

```php theme={null}
$fluent = fluent(['a' => 1, 'b' => 2]);

$attributes = $fluent->getAttributes();
// ['a' => 1, 'b' => 2]
```

### De ArrayAccess-interface

Fluent implementeert `ArrayAccess`, dus je kunt ermee werken als met een array.

```php theme={null}
$config = new Fluent();

// Zetten zoals bij een array
$config['host'] = 'localhost';
$config['port'] = 3306;

// Lezen zoals bij een array
echo $config['host']; // 'localhost'

// Bestaan controleren
if (isset($config['port'])) {
    echo $config['port'];
}

// Verwijderen
unset($config['port']);
```

### De IteratorAggregate-interface

Over een Fluent kun je met foreach itereren.

```php theme={null}
$settings = fluent([
    'debug' => true,
    'cache' => 'redis',
    'queue' => 'database'
]);

foreach ($settings as $key => $value) {
    echo "$key: $value\n";
    // debug: 1
    // cache: redis
    // queue: database
}
```

## JSON-verwerking

### toJson() — omzetten naar een JSON-string

```php theme={null}
$response = fluent([
    'success' => true,
    'data' => ['id' => 1, 'name' => 'User']
]);

$json = $response->toJson();
// {"success":true,"data":{"id":1,"name":"User"}}

// Bruikbaar als API-response
return $json;
```

### toPrettyJson() — omzetten naar geformatteerde JSON

```php theme={null}
$data = fluent([
    'users' => [
        ['id' => 1, 'name' => 'Alice'],
        ['id' => 2, 'name' => 'Bob']
    ]
]);

echo $data->toPrettyJson();
// {
//     "users": [
//         {
//             "id": 1,
//             "name": "Alice"
//         },
//         {
//             "id": 2,
//             "name": "Bob"
//         }
//     ]
// }
```

### De JsonSerializable-interface

Fluent implementeert `JsonSerializable`, dus je kunt de klasse direct omzetten met `json_encode()`.

```php theme={null}
$fluent = fluent(['status' => 'ok', 'code' => 200]);

$json = json_encode($fluent);
// {"status":"ok","code":200}

$data = json_decode($json, true);
// ['status' => 'ok', 'code' => 200]
```

## Toestand controleren

### isEmpty() / isNotEmpty()

```php theme={null}
$empty = new Fluent();
$filled = fluent(['value' => 1]);

$empty->isEmpty();      // true
$empty->isNotEmpty();   // false

$filled->isEmpty();     // false
$filled->isNotEmpty();  // true
```

## De Conditionable-trait

Fluent gebruikt de `Conditionable`-trait en ondersteunt dus conditionele verwerking.

```php theme={null}
$config = fluent(['env' => 'production']);

$config
    ->when($config->env === 'production', function ($fluent) {
        $fluent->debug = false;
        $fluent->cache = 'redis';
    })
    ->when($config->env === 'local', function ($fluent) {
        $fluent->debug = true;
        $fluent->cache = 'array';
    });

echo $config->debug;
echo $config->cache;
```

Met de methodes `when()` / `unless()` schrijf je configuratie op basis van voorwaarden op een vloeiende manier.

## De Macroable-trait

Fluent gebruikt ook de `Macroable`-trait, waarmee je dynamisch methodes kunt toevoegen.

```php theme={null}
use Illuminate\Support\Fluent;

// Definiëren in de boot()-methode van een provider
Fluent::macro('isProduction', function () {
    /** @var Fluent $this */
    return $this->env === 'production';
});

Fluent::macro('isDevelopment', function () {
    /** @var Fluent $this */
    return $this->env === 'development';
});

// Gebruik
$config = fluent(['env' => 'production']);

if ($config->isProduction()) {
    // Verwerking voor productie
}
```

## Praktische use cases

### Een API-responsebuilder

```php theme={null}
namespace App\Support;

use Illuminate\Support\Fluent;

class ApiResponse
{
    public static function success($data = null, string $message = 'Success'): string
    {
        return fluent([
            'success' => true,
            'message' => $message,
            'data' => $data,
            'timestamp' => now()->toIso8601String()
        ])->toJson();
    }

    public static function error(string $message, int $code = 400): string
    {
        return fluent([
            'success' => false,
            'message' => $message,
            'code' => $code,
            'timestamp' => now()->toIso8601String()
        ])->toJson();
    }
}

// Gebruik in een controller
public function store(Request $request)
{
    $user = User::create($request->validated());

    return response()->json(
        json_decode(ApiResponse::success(['id' => $user->id]))
    );
}
```

### Een configbuilder

```php theme={null}
$dbConfig = fluent()
    ->host(env('DB_HOST', 'localhost'))
    ->port(env('DB_PORT', 3306))
    ->database(env('DB_DATABASE', 'laravel'))
    ->username(env('DB_USERNAME', 'root'))
    ->password(env('DB_PASSWORD', ''))
    ->charset('utf8mb4')
    ->collation('utf8mb4_unicode_ci')
    ->when(env('APP_ENV') === 'production', function ($config) {
        $config->sslmode('require');
        $config->sslcert(env('DB_SSL_CERT'));
    });

// De instellingen valideren en gebruiken
config(['database.connections.mysql' => $dbConfig->toArray()]);
```

### Requestparameters valideren en omzetten

```php theme={null}
namespace App\Services;

use Illuminate\Support\Fluent;

class SearchFilter
{
    public function apply(array $params): Fluent
    {
        $filter = fluent()
            ->page($params['page'] ?? 1)
            ->perPage($params['per_page'] ?? 15)
            ->sort($params['sort'] ?? 'created_at')
            ->order($params['order'] ?? 'desc')
            ->when(isset($params['search']), function ($f) use ($params) {
                $f->search = $params['search'];
            })
            ->when(isset($params['status']), function ($f) use ($params) {
                $f->status = $params['status'];
            });

        // Paginaberekening
        $filter->offset = ($filter->page - 1) * $filter->perPage;

        return $filter;
    }
}

// Gebruik
$filter = app(SearchFilter::class)->apply(request()->all());

$users = User::query()
    ->when($filter->has('search'), fn ($q) => $q->search($filter->search))
    ->when($filter->has('status'), fn ($q) => $q->where('status', $filter->status))
    ->orderBy($filter->sort, $filter->order)
    ->offset($filter->offset)
    ->limit($filter->perPage)
    ->get();
```

### Modellen combineren met Fluent

```php theme={null}
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Fluent;

class Post extends Model
{
    protected $casts = [
        'metadata' => 'json'
    ];

    public function getMetadataAttribute($value): Fluent
    {
        return new Fluent($value ?? []);
    }

    public function setMetadataAttribute($value): void
    {
        if ($value instanceof Fluent) {
            $this->attributes['metadata'] = $value->toJson();
        } else {
            $this->attributes['metadata'] = json_encode($value);
        }
    }
}

// Gebruik
$post = new Post();

$post->metadata = fluent()
    ->title('SEO Title')
    ->description('Meta Description')
    ->keywords(['laravel', 'fluent', 'tutorial'])
    ->author('Laravel Community');

$post->save();

// Lezen
$post = Post::first();
echo $post->metadata->title; // 'SEO Title'
echo $post->metadata->author; // 'Laravel Community'
```

### Formulierdata normaliseren

```php theme={null}
namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Fluent;

class CreateUserRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'name' => 'required|string',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:8|confirmed',
            'role' => 'in:user,admin',
            'preferences' => 'json',
        ];
    }

    // Gevalideerde data teruggeven als Fluent
    public function toFluent(): Fluent
    {
        $preferences = is_string($this->preferences)
            ? json_decode($this->preferences, true)
            : $this->preferences;

        return fluent([
            'name' => $this->name,
            'email' => $this->email,
            'password' => bcrypt($this->password),
            'role' => $this->role ?? 'user',
            'preferences' => new Fluent($preferences ?? [])
        ]);
    }
}

// Gebruik in een controller
public function store(CreateUserRequest $request)
{
    $data = $request->toFluent();

    $user = User::create($data->all());

    return response()->json(['success' => true, 'user_id' => $user->id]);
}
```

## Vergelijking met andere klassen

### Fluent vs array

| Functionaliteit     | Fluent               | Array                   |
| ------------------- | -------------------- | ----------------------- |
| Propertytoegang     | `$fluent->name`      | `$array['name']`        |
| Method chaining     | ✓ Ondersteund        | ✗ Niet                  |
| JSON-conversie      | `toJson()`-methode   | `json_encode()`-functie |
| Puntnotatie         | ✓ `get('user.name')` | ✗ Handmatig             |
| Toestandscontrole   | `isEmpty()`          | `empty()`-functie       |
| Dynamische methodes | Macroable            | ✗ Niet mogelijk         |

### Fluent vs Model

| Functionaliteit     | Fluent         | Model         |
| ------------------- | -------------- | ------------- |
| DB-persistentie     | ✗ Geen         | ✓ Automatisch |
| Geheugenefficiëntie | ✓ Lichtgewicht | ✗ Zwaar       |
| Relaties            | ✗ Geen         | ✓ Ondersteund |
| Casts               | ✗ Geen         | ✓ Ondersteund |
| Validatie           | ✗ Geen         | ✓ Ondersteund |
| Vloeiende API       | ✓ Aanwezig     | △ Beperkt     |

## Details van de interne implementatie

```php theme={null}
class Fluent
{
    protected $attributes = [];

    // Magic method: toegang tot een niet-bestaande property
    public function __get($key)
    {
        return $this->value($key);
    }

    // Magic method: zetten van een niet-bestaande property
    public function __set($key, $value)
    {
        $this->offsetSet($key, $value);
    }

    // Magic method: aanroep van een niet-bestaande methode
    // De methodenaam wordt direct de propertysleutel
    public function __call($method, $parameters)
    {
        $this->attributes[$method] = count($parameters) > 0
            ? $parameters[0]
            : true;

        return $this;
    }
}
```

Als er geen macro geregistreerd is, zet de `__call`-methode de waarde in de attributen met de methodenaam als propertysleutel en geeft `$this` terug. Dat maakt method chaining mogelijk.

<Tip>
  Fluent gebruikt de volgende traits, die elk verschillende functionaliteit bieden:

  * **Conditionable** — conditionele verwerking met `when()` / `unless()`
  * **InteractsWithData** — databewerkingsmethodes zoals `data()`
  * **Macroable** — dynamisch methodes toevoegen
</Tip>

## Volgende stappen

<Card title="Collection-klasse" icon="arrow-right-arrow-left" href="/nl/advanced/collection-deep-dive">
  Een verdieping in de Collection-klasse, die met meerdere elementen werkt.
</Card>

<Card title="Conditionable-trait" icon="arrow-right-arrow-left" href="/nl/advanced/conditionable">
  Leer de Conditionable-trait, waarmee je conditionele verwerking vloeiend opschrijft.
</Card>

<Card title="Macroable-trait" icon="arrow-right-arrow-left" href="/nl/advanced/macroable">
  Leer de Macroable-trait, waarmee je dynamische methodes toevoegt aan bestaande klassen.
</Card>


## Related topics

- [Strings bewerken (de Str-klasse)](/nl/strings.md)
- [URL's genereren](/nl/urls.md)
- [InteractsWithData-trait](/nl/advanced/interacts-with-data.md)
- [Custom validatieregels](/nl/advanced/custom-validation-rules.md)
- [Lottery-klasse](/nl/advanced/lottery.md)
