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() when $step is less than 1. nth() selects every n-th element; a step of 0 or negative is mathematically meaningless (modulo by zero / infinite loop) and is rejected up front.

Solutions

  1. Ensure $step >= 1: max(1, (int) $step).
  2. Validate the input before calling nth().
  3. Default to a positive literal when the parameter is optional.

Example fix

// before
$every = $col->nth($userStep); // throws if $userStep = 0
// after
$every = $col->nth(max(1, (int) $userStep));
Defensive patterns

Strategy: validation

Validate before calling

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

Type guard

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

Try / catch

try {
    $every = $col->nth($userStep);
} catch (\InvalidArgumentException $e) {
    $every = $col->nth(1);
}

Prevention

When it happens

Trigger: Calling $collection->nth(0) or ->nth(-1), or passing a computed step that evaluates to <=0.

Common situations: Dynamic step derived from user input or division that rounds to 0; off-by-one in a loop counter.

Related errors


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

Appendix: 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 e0f6eb3518)