laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 28 forks source link

conditional Add method on Collection #2529

Closed runand closed 3 years ago

runand commented 3 years ago

In many cases, I find my self having to declare variables, only for doing a simple validation before adding it to a collection.

        $collection = collection();
        $var = $method->call('arg');

        if (!empty($var)) {
            $collection->add($var);
        }

instead an addIfTrue or addWhen method could be used, to adding the item to a collection if it a condition is met. example of method:

     /**
     * Add an item to the collection if it is not empty.
     *
     * @param  mixed  $item
     * @return $this
     */
    public function addIfTrue($item)
    {
        if (!empty($item)) {
            $this->items[] = $item;
        }
        return $this;
    }

example of usage:

        $collection = collection();

        $collection->addIfTrue($method->call('arg'));

I was looking at the when method on the collection, but if a lot of variables from the outside scope is needed in the callback function, it does involve writing a lot more code.

tpetry commented 3 years ago

Collection does use the Macroable trait, so you can easily add more functions to the collection class ;)

Collection::macro('addIfTrue', function($item) {
    return filled($item) ? $this->add($item) : $this;
});