Reference

Guide

$pages->when()

The when method only executes the given Closure when the first parameter is true. If the first parameter is false, the Closure will not be executed.

$pages->when(mixed $condition, Closure $callback, Closure $fallback = null): mixed

Parameters

Name Type Default Description
$condition mixed
$callback Closure
$fallback Closure null

Return type

mixed

Examples

Apply the filter method only if the first parameter evaluates to true:

$size  = get('size');
$color = get('color');
$fit   = get('fit');

$products = $page->children()
    ->when($size, function ($size) {
        return $this->filterBy('size', $size);
    })
    ->when($color, function ($color) {
        return $this->filterBy('color', $color);
    })
    ->when($price, function ($fit) {
        return $this->filterBy('style', $fit);
    });

With a fallback if the first parameter does not evaluate to true:

$sortBy = false;
$articles = $page->children()
    ->when($sortBy, function ($sortBy) {
        return $this->sortBy($sortBy);
    }, function () {
        return $this->sortBy('title');
    });

Inherited from

Kirby\Toolkit\Collection

Source code

kirby/src/Toolkit/Collection.php#L1069