简体   繁体   中英

Laravel-8 error with Cache::remember() function doesn't work

My application is returning an error when storing the cache, I saw that it was saving, but it is returning this error. Can anyone say why? Here's my function and the error:

function that returns error:

    <?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';

        return Cache::remember($keyName, $expiration, function ($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();
        });
    }
}

error:

ArgumentCountError
Too few arguments to function App\Repositories\ProductFilter\ProductFilterRepository::App\Repositories\ProductFilter\{closure}(), 0 passed in /var/www/vendor/laravel/framework/src/Illuminate/Cache/Repository.php on line 385 and exactly 1 expected
http://localhost:8888/recommended

my.env with cache settings

BROADCAST_DRIVER=log
CACHE_DRIVER=redis
REDIS_URL=redis
QUEUE_CONNECTION=sync
SESSION_DRIVER=redis
SESSION_LIFETIME=120

MEMCACHED_HOST=127.0.0.1

REDIS_HOST=redis
REDIS_PASSWORD=null
REDIS_PORT=6379
REDIS_CLIENT = redis

Does anyone know what can it be?

After thinking a little bit, I think I know what your problem is, you are using function ($keywords) , but you should be using function () use ($keywords) because, in the source code , you see that it is doing $value = $callback() , but your function is awaiting $keywords , if you want to share a value, you have to use use ($keywords) again, like your second function in the where .

So, it should be:

return Cache::remember($keyName, $expiration, function () use ($keywords) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM