Skip to content

[9.x] Add soleValue method to Collections#44309

Closed
ash-jc-allen wants to merge 3 commits into
laravel:9.xfrom
ash-jc-allen:feature/collection-sole-value
Closed

[9.x] Add soleValue method to Collections#44309
ash-jc-allen wants to merge 3 commits into
laravel:9.xfrom
ash-jc-allen:feature/collection-sole-value

Conversation

@ash-jc-allen
Copy link
Copy Markdown
Contributor

Hey! This PR proposes a small soleValue method that can be added to Collections and LazyCollections.

The new method tries to mimic the soleValue that's available in the query builder (added in this PR: #41368).

The idea behind using this is that it gives you more confidence that:

  1. Exactly one items in the collection
  2. The key definitely exists in the item that we are accessing

As a basic example, before this method, I might have written something similar to this:

$item = $collection->where('name', 'foo')->sole();

if (!array_key_exists('bar', $item)) { 
    throw new Exception('The "bar" field does not exist in the item');
}

return $item->bar;

But with the new method, I could write it like this:

return $collection->where('name', 'foo')->soleValue('bar');

If the item doesn't exist, an Illuminate\Support\InvalidKeyException exception will be thrown.

If you think this might be something worth merging and you need any changes making to it, please let me know and I'll sort it ASAP 😄

@driesvints driesvints marked this pull request as draft September 27, 2022 07:36
@driesvints
Copy link
Copy Markdown
Member

@ash-jc-allen can you rebase with 9.x? We fixed the failing build there.

@ash-jc-allen ash-jc-allen marked this pull request as ready for review September 27, 2022 10:03
@ash-jc-allen
Copy link
Copy Markdown
Contributor Author

@driesvints Sweet! I've done that now 🙂

@taylorotwell
Copy link
Copy Markdown
Member

Think I'm going to hold off on this one for now. You can macro it in.

@ash-jc-allen
Copy link
Copy Markdown
Contributor Author

That's no problem at all, I'll use a macro 🙂

@ash-jc-allen ash-jc-allen deleted the feature/collection-sole-value branch September 28, 2022 13:21
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.

3 participants