【问题标题】:Laravel , database record update is shown after page refreshLaravel,页面刷新后显示数据库记录更新
【发布时间】:2016-12-24 10:28:27
【问题描述】:

我用 session 实现了一个简单的视图计数。它按我的预期工作,但 view_count 值会立即在数据库中更新,但不会显示在视图中。我应该重新加载页面以获得预期的结果。 这是我的代码

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 ,但将它们删除为特定于问题。

【问题讨论】:

    标签: php mysql session controller laravel-5.2


    【解决方案1】:

    你没有重新加载$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');
    }
    

    【讨论】:

      猜你喜欢
      • 2016-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-26
      • 1970-01-01
      • 2013-03-14
      • 2019-04-09
      • 1970-01-01
      相关资源
      最近更新 更多