阅读(571) (6)

Laravel 8 when() {#collection-method}

2021-07-01 16:46:24 更新

when 方法的第一个参数传入为 true 时,将执行给定的回调函数:

$collection = collect([1, 2, 3]);

$collection->when(true, function ($collection) {
    return $collection->push(4);
});

$collection->when(false, function ($collection) {
    return $collection->push(5);
});

$collection->all();

// [1, 2, 3, 4]

when 相反的方法,请查看 unless 方法。