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 LazyCollection::nth($step, $offset) when $step < 1. nth yields every $step-th element using modulo ($position % $step === 0); a step of zero would cause division-by-zero and a negative step makes no sense, so the method rejects anything below 1 with an InvalidArgumentException. The PHPDoc marks step as positive-int.

Solutions

  1. Ensure step >= 1: ->nth(max(1, $step)).
  2. Validate the input before calling nth and short-circuit for invalid values.
  3. Default the parameter explicitly to a known-good value when sourced from config.

Example fix

// before
return $collection->nth($request->integer('interval'));
// after
$interval = max(1, $request->integer('interval', 1));
return $collection->nth($interval);
Defensive patterns

Strategy: validation

Validate before calling

if ($step < 1) {
    throw new \InvalidArgumentException('nth step must be >= 1');
}
return $collection->nth($step);

Type guard

$step = (is_int($step) && $step >= 1) ? $step : 1;

Try / catch

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

Prevention

When it happens

Trigger: ->nth(0), ->nth(-2); step derived from a divisor that can be zero; user-controlled 'sample every Nth' input.

Common situations: Downsampling data with a configurable interval that defaults to 0; passing a computed step from ceil(count/N) where N exceeds count.

Related errors


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

Appendix: source

Thrown at src/Illuminate/Collections/LazyCollection.php:928

    #[\Override]
    public function union($items)
    {
        return $this->passthru(__FUNCTION__, func_get_args());
    }

    /**
     * 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.');
        }

        return new static(function () use ($step, $offset) {
            $position = 0;

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

                $position++;
            }
        });
    }

    /**
     * Get the items with the specified keys.
     *

View on GitHub (pinned to e0f6eb3518)