laravel/framework · error · InvalidArgumentException

Step value must be at least 1.

Error message

Step value must be at least 1.

What it means

Thrown by Collection::nth($step) when $step < 1. nth() selects every $step-th element starting at an offset; a zero or negative step would loop forever or never advance, so it is rejected up front.

Source

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

     */
    public function union($items)
    {
        return $this->newInstance($this->items + $this->getArrayableItems($items));
    }

    /**
     * Create a new collection consisting of every n-th element.
     *
     * @param  int  $step
     * @param  int  $offset
     * @return ($step is positive-int ? static : never)
     *
     * @throws \InvalidArgumentException
     */
    public function nth($step, $offset = 0)
    {
        if ($step < 1) {
            throw new InvalidArgumentException('Step value must be at least 1.');
        }

        $new = [];

        $position = 0;

        foreach ($this->slice($offset)->items as $item) {
            if ($position % $step === 0) {
                $new[] = $item;
            }

            $position++;
        }

        return $this->newInstance($new);
    }

    /**

View on GitHub (pinned to bd6b5437e6)

Solutions

  1. Clamp the step: $collection->nth(max(1, $step)).
  2. Validate input before calling: if ($step >= 1) { ... }.
  3. Use a fixed literal step when the intent is a known cadence (e.g. every 2nd).
  4. Re-check the math that produced the step value.

Example fix

// before
$everyNth = $collection->nth($step);

// after
$everyNth = $collection->nth(max(1, (int) $step));
Defensive patterns

Strategy: validation

Validate before calling

$step = max(1, (int) $step);
$everyNth = $collection->nth($step);

Type guard

function isValidNthStep(int $step): bool {
    return $step >= 1;
}

Try / catch

try {
    $everyNth = $collection->nth($step);
} catch (\InvalidArgumentException $e) {
    $everyNth = $collection->nth(1);
}

Prevention

When it happens

Trigger: Calling $collection->nth(0), nth(-1), or passing a computed step that resolves to 0/negative.

Common situations: Step derived from a division that can yield zero (e.g. intdiv(count, chunkSize) when chunkSize >= count); user-supplied input not validated; off-by-one in paging math.

Related errors


AI-assisted analysis of laravel/framework@bd6b5437e6 (2026-08-06). Data as JSON: /data/errors/7582ad66d4370100.json. Report an issue: GitHub.