laravel 5.5 caching error "Serialization of 'Closure' is not allowed"

Viewed 4180

I was trying to store a complete page view to cache, but error of "Serialization of 'Closure' is not allowed" happened. in controller my code was something like this :

$view = Cache::remember('articles_index', 5, function () {
    return view('template.blade.php'); // this is some rendered html string
});

I didn't know the reason, so tried to Google it to find out, but google results was not exactly what I wanted... After a while I find a temporary solution.

$view = Cache::remember('articles_index', 5, function () {
    return htmlspecialchars(view('template.blade.php'));
});

this way of caching works, but it may broke some parts of html. still trying to find the perfect solution...

this question may update several times...

1 Answers

Your first example is trying to cache a View object, not HTML (a string). Views need to be rendered, turned into string output.

(string) view(...) or view(...)->render() would give you a string.

When you are returning views from routes Laravel knows to render them for you.

Related