[9.x] allow Collection random()
to accept a callable
#43028
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
this allows the user to, rather than passing an int directly, pass a closure that can reference back to the original Collection in case they need to reference the size of the Collection
a little confusing, so here's an example:
We have a
User
andComment
s.User
s can have manyComment
s. Let's say we want to show 5 random comments from aUser
on a dashboard.This probably seems fine, but we run into an issue if the
User
doesn't have at least 5 comments, and Laravel will throw anInvalidArgumentException
. So we want to amend this to say we want 5 comments or the total count of the comments, whichever is smaller. In order to do this currently, you need to use a temporary variable.With this PR you'll now be able to chain this entire call:
I'm still a little new to the generics docblocks, so LMK if that needs an adjustment.