framework: [5.1] Collection random with value 0 or 1 does not return a collection.

Hey,

I just notices, that the random function in a collection does not return a new collection if the argument is explicitly set to one. I would like this to work, because this way I can get a random number between 1 and x or even 0 and x and deal with the returned value the same.

With the current implementation I would have to somehow check if I got a collection or an item back.

I would love it, if $collection->random(x) where x != null would always return a collection, and $collection->random() would always return an item. This would make it much easier to work with. Thanks.

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 19 (8 by maintainers)

Most upvoted comments

I agree with @lukasoppermann. Having different return types depending on the value (not the type) is very bad design. It’s also prone to bugs that are hard to find if we pass any dynamic value as the $amount parameter.

Hey @GrahamCampbell, could you reopen this issue?

I think there is a valid reason to change this design, as other methods work like this as well:

  • take(x) for example returns a collection with 0 or 1 as the value
  • slice(x,y) also returns a collection if 0 or 1 as the second argument (length)
  • where() always returns a collection, also if only one item is found
  • splice(x,y) returns a collection if 0 or 1 as the second argument (length)

In short any method that can return one or more items, always returns a collection, no matter if 0, 1 or more items are returned. This is a common practise and sensible to use.

However, random is a mix, as the random() call with no argument is much like last() where you know only one item is returned.

But random($n) is much like the ones above, where $n could be anything from 0 to 100 and it might even be a random value within. So here you would expect a collection to be returned, no matter what number $n is, just like when randomly assigning a number to take.

Thus I would argue, it would be better for all, and easier to use, if a collection is always returned when $n is provided, while an item is always returned when no $n is provided.

Random without an argument returning an item makes sense. This is similar to a Boolean $collection where no value == false.

But to have a different type of return value depending on the int seems not optimal. This just makes it complicated.

With the “new” idea a user who wants an item just calls random without and argument. If you want a collection, you provide the argument and get a collection, no matter if you provide a 0, 1, or 15.

This would make it easier to work with, without reducing functionally in any way.