duanguane1670 2016-08-17 08:44
浏览 63
已采纳

Laravel,页面刷新后显示数据库记录更新

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.

  • 写回答

1条回答 默认 最新

  • doudiao2335 2016-08-17 08:50
    关注

    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');
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部