addIf for Laravel Collections

I wanted to add an item to a Laravel Collection, based on a truthy condition. In the script, I quickly jumped for the basic if syntax, but then wondered if there was a nicer way.

if ($condition) {

Laravel provides a lot of “syntax sugar” allowing for more fluent code. There are already methods such as dropIfExists for database schemas and fragmentIf for views, so I thought I might be able to use a similar method for adding an item to a collection. My initial thought was addIf would make sense.

$items->addIf($condition, $item)

However, this method doesn't exist…

Instead, in Laravel 9, collections have the when conditional method. This also exists in a few other classes and you can add the behaviour to anything using the Conditionable trait. So I can write the following;

$items->when($condition, static function (Collection $collection) use ($item): Collection {
    return $collection->add($item);

Which, err, isn't that nice. From a simple-to-read three-lines-of-code reduced down to two, but that is a lot more complex and harder to understand.

Dan Matthews suggested in the LaravelUK Slack channel about using arrow function. Although introduced in PHP 7.4 (now end-of-life), I preferred the anonymous syntax (as above), so I hadn't used them. However, the benefit, in this case, is that there is no longer the need to add the use statement to inject variables from the parent scope. Now we have one line that reads nicely.

$items->when($condition, fn () => $items->add($item));

However, I still think that an addIf method would be a nice addition and be in line with the developer experience (DX) that Laravel is known for. It would need to be paired with sibling methods such as prependIf and forgetIf to complete the set. Laravel is an open-source project, so I might try to write a pull request for these additions.