Skip to content
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
Merged

[5.7] Add whenEmpty + variants to Collection #26345

merged 1 commit into from
Nov 1, 2018

Conversation

Propaganistas
Copy link
Contributor

@Propaganistas 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
Copy link

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
@staudenmeir
Copy link
Contributor

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

@Propaganistas
Copy link
Contributor Author

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().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants