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

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

Merged
merged 2 commits into from
May 11, 2022
Merged

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

merged 2 commits into from
May 11, 2022

Conversation

stevebauman
Copy link
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
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
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