我使用 session 实现了一个简单的 View 计数。它按我的预期工作,但 view_count 值会立即在数据库中更新,但不会显示在 View 中。我应该重新加载页面以获得预期结果。 这是我的代码
public function viewArticle($slug){
$article = Article::where('slug',$slug)->first();
$articleKey = 'article_' . $article->id;
// Check session exists, if not then increment view count and create session key
if (!Session::get($articleKey)) {
Article::where('id', $article->id)->increment('view_count');
Session::put($articleKey, 1);
}
return view('main');
}
我将多个变量传递给 view ,但为了特定于问题而删除了它们。
最佳答案
您没有重新加载$article
,它保持不变,请尝试以下操作:
public function viewArticle($slug){
$article = Article::where('slug',$slug)->first();
$articleKey = 'article_' . $article->id;
// Check session exists, if not then increment view count and create session key
if(!Session::get($articleKey)){
$article->view_count++;
$article->save();
Session::put($articleKey,1);
}
return view('main');
}
关于php - Laravel,页面刷新后显示数据库记录更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39002137/