Laravel caches paging results
Preface
A good way to increase the page speed is to useCache
. The use and configuration of the Cache in Laravel is quite convenient, and reasonable use of the Cache in the project can produce unexpected results (of course, improper use will also lead to bad results ).
Problems encountered
So I wrote the following seemingly normal code:
$newsList = Cache::remember('newsList'.$uuid, $minutes, function() { return News::with('lastReplyUser', 'user') ->checked() ->recentReply() ->paginate(Config::get('page.newsListSize'));});
The result after refreshing the page surprised me and reported an error.Exception Serialization of 'Closure' is not allowed
.
Analyze problems
Enable xdebug debugging quickly. The object Paginator is returned. How can we say that Closure cannot be serialized?
As shown in the error message, this paginator object has a closure attribute, so it cannot be serialized.
With the help of powerful xdebug, I found the culprit.
Specific assignment location:/Path/To/Nidexiangmu/vendor/laravel/framework/src/Illuminate/View/Engines/EngineResolver. php 30 rows of this method
public function register($engine, Closure $resolver) { $this->resolvers[$engine] = $resolver; }
Solve the problem
Modifying the source code of the framework is not something we can do. In this case, let's save the country! Paginator cannot be cached.
Solution 1
Cache queries
$ NewsList = News: with ('lastreplyuser', 'user')-> checked ()-> whereNotIn ('id', $ selectedId)-> recentReply () -> remember ($ minutes) # Pay attention to this line-> paginate (Config: get ('page. newsListSize '));
Solution 2
Cache the content (items and links) required by paginator
$newsList = Cache::remember('newsList'.$uuid, $minutes, function() { $data = News::with('lastReplyUser', 'user') ->checked() ->recentReply() ->paginate(Config::get('page.newsListSize')); return ['result' => $data->getItems(), 'links' => (string)$data->links()];});
Summary
Note: * in solution 2 *links()
* After this method is called, the mandatory string Conversion is used because the returned content isview
Object, and view object attributes have closures, so do not try to serialize (including cache operations such as operations containing serial numbers) at any time) view objects and attributes have arrays or objects of view objects. (This is a good example. In fact, only view objects exist, so do not serialize or cache them ).
Deploy Laravel using Nginx in Ubuntu
Deploying Laravel 14.04 using Nginx on Ubuntu 5.0
This article permanently updates the link address: