Resources

Conditions

Render a member for some resources or some requests, without breaking the definition.

A condition is a closure, read for each resource rendered. It never runs when the hook runs, so the member stays in the definition and fields / include may still name it.

public function toAttributes(Request $request): iterable
{
    return [
        'name' => $this->string(),
        // a conditional attribute
        'secret' => $this->string()
            ->when(fn() => $request->user()?->isAdmin() ?? false),
        // several members under one condition
        $this->applyWhen(fn() => $request->user()?->isAdmin() ?? false, [
            'first-secret' => $this->integer(fn() => 123),
            'second-secret' => $this->float(fn() => 456.789),
        ]),
    ];
}
Laravel's $this->when($condition, $value), $this->mergeWhen() and $this->whenHas() give plain values, evaluated once for the whole response: they are refused in a hook. So is an if around a member.

On a value

ModifierThe value is rendered
->when(fn($model, $attribute) => …)when the closure returns true; it runs before the value is read
->unless(fn() => …)unless the closure returns a truthy value
->whenNotNull()when it is not null
->whenFilled()when it is not empty
->whenHas(?string $key)when the model has the attribute
->whenLoaded(string $relation)when the relation is loaded on the model
->whenAppended(?string $attribute)when the accessor is appended to the model
->whenInFields()only when fields[type] names it explicitly

A value whose condition fails is never computed.

protected ?bool $autoWhenHas = true; on a resource applies whenHas() to every value read from a key of the model; describer.when-has does it for the whole application, for some scopes (['attributes', 'resource-meta', 'meta']) or all.

On a relationship

->when() and ->unless() work on relationships too; their closure receives (null, $model). For the linkage of a relationship, see Relationships: whenIncluded(), whenLoaded(), whenPivotLoaded(), can().

On the request

Helper (keyed by the member name)Renders the value
$this->whenInFields($request, 'attribute', $value)only when fields requests the attribute
$this->whenInIncludes($request, 'relationship', $value)only when include names the relationship
protected function toResourceMeta(Request $request): ?iterable
{
    return [
        'comments_count' => $this->whenInIncludes(
            $request,
            'comments',
            $this->integer(fn(Post $post) => $post->comments->count()),
        ),
    ];
}

At a revision, both test the name the field has at it.

Changes of meaning across revisions

A condition on the revision of the client is a guard, not a condition: a field that changes shape declares its history with ->was() instead.