laravel/framework · error · InvalidArgumentException

Cache value for key [ ] must be an integer, given.

Error message

Cache value for key [%s] must be an integer, %s given.

What it means

Thrown by Repository::integer() when the cached value is neither a real int nor a string that filter_var(FILTER_VALIDATE_INT) accepts. The method first tries is_int(), then attempts integer coercion, and only throws when both fail. Numeric strings like '42' pass; 'abc', floats like 3.14, bools, arrays, and null do not.

Solutions

  1. Pass an int default: Cache::integer('key', 0).
  2. Ensure the stored value is an int or an integer-string at write time.
  3. Pre-coerce with (int) before Cache::put if the source is float/bool.

Example fix

// before
$views = Cache::integer('post.views'); // throws on miss
// after
$views = Cache::integer('post.views', 0);
Defensive patterns

Strategy: validation

Validate before calling

$raw = Cache::get($key);
if ($raw !== null && ! is_int($raw) && filter_var($raw, FILTER_VALIDATE_INT) === false) {
    // not integer-coercible; normalize or abort
}
$val = Cache::integer($key, 0);

Type guard

function isCacheIntegerable(mixed $value): bool {
    return is_int($value) || filter_var($value, FILTER_VALIDATE_INT) !== false;
}

Try / catch

try {
    $count = Cache::integer('visits');
} catch (\InvalidArgumentException $e) {
    $count = 0;
}

Prevention

When it happens

Trigger: Calling Cache::integer('key') where the stored value is a non-numeric string, a float, a bool, an array, or null (missing key with no default).

Common situations: Storing a float-formatted counter ('1.5') and reading as integer; cache miss without default; storing booleans and expecting 0/1 coercion (which does NOT happen here).

Related errors


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

Appendix: source

Thrown at src/Illuminate/Cache/Repository.php:280

     * @param  (\Closure():(int|null))|int|null  $default
     *
     * @throws \InvalidArgumentException
     */
    public function integer($key, $default = null): int
    {
        $key = enum_value($key);

        $value = $this->get($key, $default);

        if (is_int($value)) {
            return $value;
        }

        if (filter_var($value, FILTER_VALIDATE_INT) !== false) {
            return (int) $value;
        }

        throw new InvalidArgumentException(
            sprintf('Cache value for key [%s] must be an integer, %s given.', $key, gettype($value))
        );
    }

    /**
     * Retrieve a float item from the cache.
     *
     * @param  \UnitEnum|string  $key
     * @param  (\Closure():(float|null))|float|null  $default
     *
     * @throws \InvalidArgumentException
     */
    public function float($key, $default = null): float
    {
        $key = enum_value($key);

        $value = $this->get($key, $default);

View on GitHub (pinned to e0f6eb3518)