Problem with caching Collections with Redis

I just work a lot with caching queries on my website with redis.

I realized I had to change Models or Collections to arrays before I can cache them, so I did.

But well, I reached some point where it’s impossible to do this: With pagination, my query return a LengthAwardPagianator object which I need to build the pagination in the frontend. But I cannot cache this. So it’s kinda a dead end for caching paginated lists.

Then I started searching and found a lot of examples where people cached models or collections and it worked, for example like in this video:

So now I further tested and tested and found an issue: Redis.

        $test = Cache::rememberForever('mytest', function () {
            return User::get();
            // Second test: return User::paginate();

This little codesnippet which should simply fetch and store the Rainlab users does work with cache driver “array”, but does not work with Redis. The following error message appears:

Exception: Serialization of 'Closure' is not allowed in ..

I could solve it with the ->toArray() method, but well… then the pagination and other methods I attached to a model (for ex) dont work.

So: I guess this might be a bug, since I do not expect a certain piece of code to work with the one, but not with the other caching method.

Thanks a lot for any help already. ^^

Some additional info, maybe it helps to solve the problem:

In this video, the Laravel guy clearly shows that an Eloquent Collection can be cached (4:38):

However, if I try to cache my October\Rain\Database\Collection, the Exception: Serialization of 'Closure' is not allowed happens.

What’s the difference between Eloquent and October Collections so this happens here?

Any possibility to fix it?

I’ve flagged this as a known issue for investigation. Thanks @LordRazen

1 Like

A fix for this should be included in v3.4

1 Like

@daft is there any patch or any possibility to make it work on OctoberCMS v2? Perhaps you can tell what and where should be changed to make it work on OctoberCMS v2?

When I use this:

$categories = Cache::rememberForever('categories', function () {
    return Category::get();

I have the following error:

Serialization of ‘Closure’ is not allowed

I figured out that under the hood this code throws an error:


And I have error only if my model uses Validation or Sortable traits.
I have figured out that error comes because these traits have closures in the constructor, for example:

$model->bindEvent('model.saveInternal', function($data, $options) use ($model) {

Currently I can not switch my project to OctoberCMS v3.4. How can I solve this error in October v2? Thanks a lot!