duanguane1670 2016-08-17 16: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 16: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');
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启