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 is less than 1. nth() returns every n-th element, so a step of 0 or negative is meaningless (0 would yield nothing, negative is undefined). The guard ensures a positive integer step.

Source

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

    #[\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 bd6b5437e6)

Solutions

  1. Pass a step >= 1; clamp with max(1, $step).
  2. Default the source value to a sensible positive integer.
  3. Guard the call when the step variable may be 0 or negative.

Example fix

// before
$samples = $lazy->nth($samplingRate);

// after
$samples = $lazy->nth(max(1, (int) $samplingRate));
Defensive patterns

Strategy: validation

Validate before calling

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

Type guard

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

Try / catch

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

Prevention

When it happens

Trigger: Calling $lazy->nth(0) or $lazy->nth(-2). Often $step is derived from a modulo/division that can produce 0, or from request input.

Common situations: Sampling every n-th row from a dataset where n is config-driven and the config is unset (0). Computing step from item count when the collection is empty.

Related errors


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