0

Error is:

Serialization of 'Closure' is not allowed

Error at:

.../vendor/laravel/framework/src/Illuminate/Cache/RedisStore.php:295

Throws when remembering forever on Cache for the first time. After second try (when reloading browser) it works as it should work.

public function cache() 
{
    $task = $this;

    return Cache::rememberForever('apply:' . $task->apply->slug . ':' . $task->slug, function () use ($task) {
        return $task;
    });
}

Interesting part is this. So it works on caching $apply on Apply's index page. (The code is the same)

Note: This issue is related to Redis directly. Please don't mention old questions about serialization. You can check official Laravel 6.x documentation too. Everything is added related to it: https://laravel.com/docs/6.x/cache#retrieving-items-from-the-cache

  • 1
    Possible duplicate of [Exception: Serialization of 'Closure' is not allowed](https://stackoverflow.com/questions/13734224/exception-serialization-of-closure-is-not-allowed) – James Nov 22 '19 at 11:58
  • No. It's related to Redis cache. I mentioned above – Samir Mammadhasanov Nov 22 '19 at 12:03
  • 1
    I may be wrong, but I believe it has nothing to do with your Redis cache, but the fact that you are literally trying to serialize an anonymous function (a closure). Why do you need to wrap it in a function anyway, why can't you just cache `$task`? – James Nov 22 '19 at 12:05
  • because `rememberForever()` only accepts callback function. Not variables – Samir Mammadhasanov Nov 22 '19 at 12:07
  • @James check this please: https://laravel.com/docs/6.x/cache#retrieving-items-from-the-cache – Samir Mammadhasanov Nov 22 '19 at 12:08
  • Where does it say that? The docs literally say `Cache::forever(‘key’, ‘value’);` – James Nov 22 '19 at 12:09
  • Why are you trying the store a class in the cache? In the docs example they are using a collection. Your error is due to the fact that `$task` cannot be serialised. That’s a PHP limitation. – James Nov 22 '19 at 12:11
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/202886/discussion-between-samir-mammadhasanov-and-james). – Samir Mammadhasanov Nov 22 '19 at 12:16

1 Answers1

0

I fixed it by manually storing and returning data if it exists on cache (how rememberForever() should be work).

public function cache () {

    $slug = 'task:'.$this->slug;

    if(Cache::has($slug)) return Cache::get($slug);

    if(!Cache::put($slug, $this)) throw new ProtocolException(1045);

    return Cache::get($slug);
}