You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 8使用Cache::remember()存储缓存触发ArgumentCountError错误如何解决

问题原因
  • 报错核心为Cache::remember()的回调闭包参数声明不符合Laravel规范:Laravel执行缓存未命中后的回调逻辑时,不会给该闭包传入任何参数,你在闭包参数列表中声明了必填参数$keywords,系统无参数传入就触发了参数不足的报错。
  • 你已经通过use ($keywords)语法引入了上层作用域的$keywords变量,闭包参数列表里的$keywords属于多余声明,反而会覆盖上层传入的变量,即使没有参数报错也会导致查询逻辑异常。
  • 额外潜在问题:当前缓存键为固定值productsRecommended,不同搜索关键词返回的结果会共用同一个缓存键,会出现不同搜索条件返回相同错误结果的问题。
修复方案

直接移除闭包参数列表的$keywords声明即可,同时建议优化缓存键规则避免逻辑异常,修改后代码如下:

<?php

namespace App\Repositories\ProductFilter;

use App\Models\Product;
use App\Repositories\Contracts\IProductFilterRepository;
use Illuminate\Support\Facades\Cache;

class ProductFilterRepository implements IProductFilterRepository
{
   
    public function getProductsRecommendations($keywords)
    {
        $expiration = 10;
        // 优化缓存键:将关键词序列化后哈希,不同搜索条件对应不同缓存
        $keyName = 'productsRecommended_' . md5(serialize($keywords));

        // 仅移除闭包参数列表的$keywords即可
        return Cache::remember($keyName, $expiration, function () use ($keywords) {
            return  Product::query()->where(function ($productsAll) use ($keywords) {
                if ($keywords) {
                    foreach ($keywords as $keyword)
                        $productsAll->orWhere('title', 'LIKE', '%' . $keyword . '%')
                            ->orWhere('description', 'LIKE', '%' . $keyword . '%')
                            ->orWhere('code', 'LIKE', '%' . $keyword . '%');
                }
            })->where('status', 'active')->get();
        });
    }
}

核心修改点

  1. 移除回调闭包参数列表中的$keywords声明,仅通过use语法引入上层作用域的变量,符合Laravel缓存回调的调用规则
  2. 优化缓存键生成逻辑,将搜索关键词序列化后哈希加入键名,避免不同搜索条件共用缓存的逻辑错误

内容的提问来源于stack exchange,提问作者Danilobol

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 19:54:05