John Dorsey John Dorsey - 3 months ago 22
PHP Question

Laravel , database record update is shown after page refresh

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.

Answer

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');
}
Comments