Laravel - Collections - Method When

The when method will execute the given callback when the first argument given to the method evaluates to 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]
	

A second callback may be passed to the when method. The second callback will be executed when the first argument given to the when method evaluates to false:

    
    $collection = collect([1, 2, 3]);
    
    $collection->when(false, function ($collection) {
        return $collection->push(4);
    }, function ($collection) {
        return $collection->push(5);
    });
    
    $collection->all();
    
    // [1, 2, 3, 5]
	

For the inverse of when, see the unless method.