Reputation: 17
I implemented a simple view count with session . It is working as I expected but the view_count value is updated immediately in database but is not shown in view. I should reload page to get the expected result. Here is my code
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');
}
I pass multiple variables to view , but removed them to be specific to question.
Upvotes: 0
Views: 386
Reputation: 409
You did not reload the $article
, it remain the same, try this instead:
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');
}
Upvotes: 1