laravel/framework · error · InvalidArgumentException
You requested items, but there are only items available.
Error message
You requested {$requested} items, but there are only {$count} items available. What it means
Thrown by Arr::random() when $number (items requested) exceeds count($array). The check runs before any short-circuit for empty arrays, so even requesting 1 from an empty array triggers it.
Solutions
- Clamp $number to the array size: $n = min($n, count($array)).
- Guard for emptiness: if (empty($array)) return []; before calling.
- Validate the requested count against count($array) upstream.
Example fix
// before $pick = Arr::random($rows, 3); // throws if < 3 rows // after $n = min(3, count($rows)); $pick = $n > 0 ? Arr::random($rows, $n) : [];
Defensive patterns
Strategy: validation
Validate before calling
$count = count($array);
if ($count === 0) {
$pick = [];
} else {
$n = min($requested, $count);
$pick = Arr::random($array, $n);
} Type guard
// no type guard; runtime count check
function safeRandomCount(int $requested, int $available): int {
return max(0, min($requested, $available));
} Try / catch
try {
$pick = Arr::random($rows, 3);
} catch (\InvalidArgumentException $e) {
$pick = [];
} Prevention
- Clamp the requested count to the array length.
- Handle empty arrays before calling Arr::random().
- Validate user-supplied counts before use.
When it happens
Trigger: Calling Arr::random([], 1), Arr::random([1,2], 5), or passing a dynamic $number larger than the data set.
Common situations: Randomizing from a possibly-empty query result; user-supplied count parameter; off-by-one when source array was filtered down.
Related errors
- Array value for key [ ] must be a boolean, found.
- Array value for key [ ] must be a float, found.
- Array value for key [ ] must be a string, found.
- Array value for key [ ] must be an array, found.
- Array value for key [ ] must be an integer, found.
AI-assisted analysis of laravel/framework@e0f6eb3518 (2026-08-11).
Data as JSON: /api/errors/494348803db5fd08.
Report an issue: GitHub.
Appendix: source
Thrown at src/Illuminate/Collections/Arr.php:978
/**
* Get one or a specified number of random values from an array.
*
* @param array $array
* @param int|null $number
* @param bool $preserveKeys
* @return ($number is null ? mixed : array)
*
* @throws \InvalidArgumentException
*/
public static function random($array, $number = null, $preserveKeys = false)
{
$requested = is_null($number) ? 1 : $number;
$count = count($array);
if ($requested > $count) {
throw new InvalidArgumentException(
"You requested {$requested} items, but there are only {$count} items available."
);
}
if (empty($array) || (! is_null($number) && $number <= 0)) {
return is_null($number) ? null : [];
}
$keys = (new Randomizer)->pickArrayKeys($array, $requested);
if (is_null($number)) {
return $array[$keys[0]];
}
$results = [];
if ($preserveKeys) {
foreach ($keys as $key) {View on GitHub (pinned to e0f6eb3518)