laravel/framework · error · InvalidArgumentException

Number of shifted items may not be less than zero.

Error message

Number of shifted items may not be less than zero.

What it means

Thrown by Collection::shift($count) when $count is negative. The method removes and returns the first N items; a negative count has no semantic meaning and is rejected. Zero and positive values are valid (0 returns an empty collection, 1 returns a single item).

Solutions

  1. Clamp to zero: $collection->shift(max(0, $count)).
  2. Validate $count >= 0 before calling.
  3. Use the default shift() (count = 1) when only one item is needed.

Example fix

// before
$head = $col->shift($n); // throws if $n < 0
// after
$head = $col->shift(max(0, $n));
Defensive patterns

Strategy: validation

Validate before calling

$count = max(0, (int) $count);
$result = $collection->shift($count);

Type guard

function isNonNegativeCount(int $count): bool { return $count >= 0; }

Try / catch

try {
    $head = $col->shift($n);
} catch (\InvalidArgumentException $e) {
    $head = $col->shift(0);
}

Prevention

When it happens

Trigger: Calling $collection->shift(-1) or passing a computed $count that goes negative.

Common situations: Count derived from arithmetic (e.g. count - offset) that can go negative; user-supplied pagination input not bounded.

Related errors


AI-assisted analysis of laravel/framework@e0f6eb3518 (2026-08-11). Data as JSON: /api/errors/85379715c74d186b. Report an issue: GitHub.

Appendix: source

Thrown at src/Illuminate/Collections/Collection.php:1271

        if ($position === $keys->count() - 1) {
            return null;
        }

        return $this->get($keys->get($position + 1));
    }

    /**
     * Get and remove the first N items from the collection.
     *
     * @param  int<0, max>  $count
     * @return ($count is 1 ? TValue|null : static<int, TValue>)
     *
     * @throws \InvalidArgumentException
     */
    public function shift($count = 1)
    {
        if ($count < 0) {
            throw new InvalidArgumentException('Number of shifted items may not be less than zero.');
        }

        if ($this->isEmpty()) {
            return null;
        }

        if ($count === 0) {
            return $this->newInstance();
        }

        if ($count === 1) {
            return array_shift($this->items);
        }

        $results = [];

        $collectionCount = $this->count();

View on GitHub (pinned to e0f6eb3518)