When I start a query to get a certain number of random models
$object = Model::all()->random(10);
I get this error:
local.ERROR: 'exception InvalidArgumentException' with message 'You requested 10 items, but there are only 1 items in the collection' in D:\www!Chiny_2016\vendor\laravel\framework\src\Illuminate\Support\Collection.php:584
Feature suggestion:
maybe the random method should output as many as there is, instead of crashing?
This is by design – a programmer that requests 10 items should also be able to expect 10 items.
... unless an user deletes some/all items - on purpose or by accident. Then it becomes a bug, not a feature.
Not quite sure what you mean? Whether records are deleted or not should not matter to the random method? Can you give an example when this would be a bug?
sure.
I have a dynamically populated set of quotes of the day for one month. These are quotes that were upvoted in last 24hrs.
Usually their number is around 40, but during Christmas their number dropped below 10.
If current random() was foolproof, it would create a collection with the available number even if the number is below 10.
Of course I can add extra if around the collection (and for N placing available number if it is smaller than 10... but such things should be solved app-side, in my opinion. Present solution contradicts the idea of a framework - to make programmer's work easier/faster.
The random method should definitely not be changed. In my opinion, it's up to the developer to ensure you handle edge cases of your application. The vast majority of developers will expect to get 10 items when they request 10, anything else would be inconsistent. I'll put together a PR though and we can see what Taylor thinks about it.
Thx.
In the meantime I came up with a good scenario:
Sunday evening. Football game is about to start in 60 mins.
...1 hour later...
Now my point is perfectly clear, I guess.! :)
Most helpful comment
Thx.
In the meantime I came up with a good scenario:
Sunday evening. Football game is about to start in 60 mins.
...1 hour later...
Now my point is perfectly clear, I guess.! :)