New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.7] Add whenEmpty + variants to Collection #26345

Merged
merged 1 commit into from Nov 1, 2018

Conversation

Projects
None yet
4 participants
@Propaganistas
Contributor

Propaganistas commented Nov 1, 2018

I often find myself in need of executing actions with a collection if it is / is not empty. At the moment this is possible in several ways. For example:

  • Assign the collection to a variable, then reuse the variable in when()

    $collection = collect()->filter(...);
    
    $collection->when($collection->isEmpty(), function($c) {
        return $c->push('item');
    });
  • Pipe the collection and use if or when() in there:

    collect()->filter(...)->pipe(function($collection) {
        return $collection->when($collection->isEmpty(), function($c) {
            return $c->push('item');
        });
    });

The first example seems to defeat the purpose of a collection (creating a chain of calls on a collection instance), the second example just seems to be one hell of nested closures to me.

I always add the whenEmpty() method (and variants) to my applications as macros. This allows me to fluently do the following and keep chaining:

collect()->filter(...)->whenEmpty(function($c) {
    return $c->push('item');
});

I thought it could prove useful to suggest these shortcuts for implementation. If not I'lll happily continue defining these as macros.

@hichxm

This comment has been minimized.

hichxm commented Nov 1, 2018

I too often find myself doing macros to execute a callback under any condition. I think it's a good start to add a series of features of this type to the collection.

@taylorotwell taylorotwell merged commit dfe84e6 into laravel:5.7 Nov 1, 2018

1 check passed

continuous-integration/travis-ci/pr The Travis CI build passed
Details
@staudenmeir

This comment has been minimized.

Contributor

staudenmeir commented Nov 1, 2018

Isn't unlessNotEmpty() just the same as whenEmpty()? And unlessEmpty() the same as whenNotEmpty()?

abdala added a commit to cgauge/framework that referenced this pull request Nov 2, 2018

@Propaganistas

This comment has been minimized.

Contributor

Propaganistas commented Nov 2, 2018

Isn't unlessNotEmpty() just the same as whenEmpty()? And unlessEmpty() the same as whenNotEmpty()?

It surely is. It seemed "incomplete" to me only suggesting the whenX() variants while the Collection class offers both when() and unless().

andrey-helldar added a commit to andrey-helldar/docs that referenced this pull request Nov 8, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment