Skip to content

[9.x] Add value() collection method#42257

Merged
taylorotwell merged 2 commits into
laravel:9.xfrom
stevebauman:feature-collection-value
May 11, 2022
Merged

[9.x] Add value() collection method#42257
taylorotwell merged 2 commits into
laravel:9.xfrom
stevebauman:feature-collection-value

Conversation

@stevebauman
Copy link
Copy Markdown
Contributor

@stevebauman stevebauman commented May 4, 2022

Description

This PR adds the collect($items)->value($key) method, which operates similarly to Eloquent's $query->value($column) method, allowing you to fetch a single key's first matching value from a collection.

Example

Let's say we have a Book model with a relationship named "metadata".

This metadata() relationship has a pivot table, containing the metadata's value.

In this application, users can attach specific metadata to books, and then assign their own value via the pivot table.

With the value() collection method, we can take the eager loaded metadata, filter by the metadata key, and then retrieve the first matching pivot.value:

// John Doe
$author = $book->metadata->where('key', 'author')->value('pivot.value');

Let me know if you'd like anything adjusted or changed. Thanks for your time! 🙏

No hard feelings on closure ❤️

return data_get($value, $key, $default);
}

return $default;
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a reason you didn't use value($default) here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nope, I just didn’t think of it 😄

@taylorotwell taylorotwell merged commit 9feb9f2 into laravel:9.x May 11, 2022
chu121su12 pushed a commit to chu121su12/framework that referenced this pull request May 20, 2022
* Add `value()` collection method

* formatting

Co-authored-by: Taylor Otwell <taylor@laravel.com>
RenoLooijmans added a commit to TicketBuy/laraconfig that referenced this pull request Jun 8, 2022
The values-method in the SettingsCollection is incompatible with latest illuminate versions. Since v9.13.0.

See also laravel/framework#42257
RenoLooijmans added a commit to TicketBuy/laraconfig that referenced this pull request Jun 9, 2022
The values-method in the SettingsCollection is incompatible with latest illuminate versions. Since v9.13.0.

See also laravel/framework#42257
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.

2 participants