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

# Trait Conditionable

> Implementazione interna dei metodi when()/unless() e pattern di utilizzo.

## Cos'è il trait Conditionable

Il trait `Illuminate\Support\Traits\Conditionable` aggiunge alla tua classe i metodi `when()` e `unless()`. La sua caratteristica principale è permettere di diramare l'elaborazione in base a una condizione mantenendo la method chain.

<Info>
  Il codice sorgente reale si trova in `src/Illuminate/Conditionable/Traits/Conditionable.php`. È referenziato tramite l'alias `Illuminate\Support\Traits\Conditionable`.
</Info>

Molte classi Laravel — QueryBuilder, EloquentBuilder, Mail, Notification — utilizzano questo trait.

## Uso di base

### when() — esegue quando la condizione è vera

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

$results = collect([1, 2, 3, 4, 5])
    ->when(true, function (Collection $collection) {
        return $collection->filter(fn ($n) => $n > 2);
    });
// [3, 4, 5]
```

Se il primo argomento è vero, viene eseguito il callback passato come secondo argomento. Se è falso, viene eseguito il callback di default (terzo argomento).

```php theme={null}
$results = collect([1, 2, 3, 4, 5])
    ->when(false, function (Collection $collection) {
        return $collection->filter(fn ($n) => $n > 2);
    }, function (Collection $collection) {
        return $collection->filter(fn ($n) => $n < 3);
    });
// [1, 2]
```

### unless() — esegue quando la condizione è falsa

`unless()` è l'inverso di `when()`. Il callback viene eseguito quando la condizione è falsa.

```php theme={null}
$results = collect([1, 2, 3, 4, 5])
    ->unless(false, function (Collection $collection) {
        return $collection->take(3);
    });
// [1, 2, 3]
```

## Perché la method chain continua

Se il valore di ritorno del callback è `null`, viene restituito `$this` (l'oggetto che usa il trait). Se il callback non restituisce `null`, viene restituito quel valore.

```php theme={null}
// viene restituito $this, quindi la catena continua
$query = User::query()
    ->when($request->has('active'), function ($query) {
        $query->where('active', true); // restituisce void / null
    })
    ->when($request->filled('name'), function ($query) use ($request) {
        $query->where('name', 'like', "%{$request->name}%");
    })
    ->orderBy('created_at', 'desc');
```

Nel codice sorgente è implementato così:

```php theme={null}
if ($value) {
    return $callback($this, $value) ?? $this;
} elseif ($default) {
    return $default($this, $value) ?? $this;
}

return $this;
```

Se il callback restituisce un valore esplicito, quel valore viene propagato al passo successivo della catena. Se non restituisce nulla (`null`), viene restituito `$this`.

## Chiamare senza argomenti — HigherOrderWhenProxy

Chiamando `when()` senza argomenti viene restituito un `HigherOrderWhenProxy`. Con esso puoi impostare la condizione a posteriori.

```php theme={null}
$query = User::query()
    ->when()->isActive()  // valuta isActive() come condizione
    ->where('role', 'admin');
```

Chiamandolo con un solo argomento ottieni un proxy che porta con sé quel valore come condizione.

```php theme={null}
// un solo argomento: passi la condizione e ottieni il proxy
$proxy = collect([1, 2, 3])->when($request->has('filter'));
// con $proxy->methodName() puoi chiamare methodName() solo se la condizione è vera
```

## Passare una closure come valore

Se passi una closure come primo argomento, il valore di ritorno di quella closure viene usato come condizione.

```php theme={null}
$results = User::query()
    ->when(
        fn ($query) => $request->filled('role'),
        fn ($query) => $query->where('role', $request->role)
    )
    ->get();
```

In questo modo puoi estrarre in un callback la logica di valutazione della condizione.

## Pattern tipico con il QueryBuilder

La costruzione dinamica delle query con `when()` è il caso d'uso più comune.

```php theme={null}
public function index(Request $request)
{
    $users = User::query()
        ->when($request->filled('search'), function ($query) use ($request) {
            $query->where('name', 'like', "%{$request->search}%")
                  ->orWhere('email', 'like', "%{$request->search}%");
        })
        ->when($request->filled('role'), fn ($q) => $q->where('role', $request->role))
        ->when($request->boolean('verified'), fn ($q) => $q->whereNotNull('email_verified_at'))
        ->when(
            $request->filled('sort'),
            fn ($q) => $q->orderBy($request->sort, $request->get('direction', 'asc')),
            fn ($q) => $q->latest()
        )
        ->paginate();

    return UserResource::collection($users);
}
```

## Applicare Conditionable a una tua classe

Basta `use` del trait per avere disponibili `when()` / `unless()`.

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

use Illuminate\Support\Traits\Conditionable;

class ReportBuilder
{
    use Conditionable;

    protected array $filters = [];
    protected bool $includeArchived = false;
    protected ?string $groupBy = null;

    public function withArchived(): static
    {
        $this->includeArchived = true;

        return $this;
    }

    public function groupBy(string $column): static
    {
        $this->groupBy = $column;

        return $this;
    }

    public function addFilter(string $column, mixed $value): static
    {
        $this->filters[$column] = $value;

        return $this;
    }

    public function build(): \Illuminate\Database\Eloquent\Builder
    {
        return Report::query()
            ->when($this->includeArchived, fn ($q) => $q->withTrashed())
            ->when($this->groupBy, fn ($q) => $q->groupBy($this->groupBy))
            ->when($this->filters, function ($q) {
                foreach ($this->filters as $column => $value) {
                    $q->where($column, $value);
                }
            });
    }
}
```

```php theme={null}
// esempio d'uso
$query = (new ReportBuilder)
    ->when($request->boolean('archived'), fn ($b) => $b->withArchived())
    ->when($request->filled('group'), fn ($b) => $b->groupBy($request->group))
    ->addFilter('status', 'published')
    ->build();
```

## Utilizzo in Mail, Notification e Response

`when()` è utilizzabile anche nella costruzione di email, notifiche e response.

```php theme={null}
use Illuminate\Mail\Mailable;
use Illuminate\Support\Traits\Conditionable;

class OrderConfirmation extends Mailable
{
    public function build(): static
    {
        return $this
            ->subject('Abbiamo ricevuto il tuo ordine')
            ->view('emails.order.confirmation')
            ->when($this->order->hasDiscount(), function (Mailable $mail) {
                $mail->attach(storage_path('discounts/coupon.pdf'));
            })
            ->when(app()->environment('production'), function (Mailable $mail) {
                $mail->bcc('archive@example.com');
            });
    }
}
```

## Quando usare tap() e quando when()

`tap()` e `when()` si assomigliano, ma hanno scopi diversi.

|                   | `tap()`                  | `when()`                                                             |
| ----------------- | ------------------------ | -------------------------------------------------------------------- |
| Scopo             | Side effect (log, debug) | Diramazione condizionale                                             |
| Valore di ritorno | Sempre `$this`           | `$this` o il valore di ritorno del callback, in base alla condizione |
| Condizione        | Nessuna                  | Presente                                                             |

```php theme={null}
// tap: usato per side effect. Il valore di ritorno è sempre $this
$user = User::find($id)
    ->tap(fn ($user) => Log::info("User {$user->id} loaded"));

// when: usato per diramare
$user = User::query()
    ->when($isAdmin, fn ($q) => $q->where('role', 'admin'))
    ->first();
```

<Tip>
  Se vuoi solo eseguire qualcosa nella catena per debug o side effect, usa `tap()`. Se vuoi cambiare comportamento in base a una condizione, usa `when()` / `unless()`.
</Tip>

## Prossimi passi

<Card title="Higher-order messages delle collection" icon="layers" href="/it/advanced/higher-order-messages">
  Impara il meccanismo di sintassi come `$collection->map->method()` e il suo utilizzo pratico.
</Card>


## Related topics

- [Classe Fluent](/it/advanced/fluent.md)
- [Trait Dumpable](/it/advanced/dumpable.md)
- [Helper tap() e trait Tappable](/it/advanced/tap.md)
- [Trait InteractsWithData](/it/advanced/interacts-with-data.md)
- [Trait InteractsWithTime](/it/advanced/interacts-with-time.md)
