首页 > 解决方案 > 如何在laravel中添加帖子的查看次数

问题描述

我正在使用 laravel 执行博客应用程序。我想在用户查看特定博客文章时跟踪文章视图的计数,无论它是注册用户还是非注册用户,它都应该只增加一次。...并且还想根据查看次数显示浏览次数最多的博客。任何人都可以协助逻辑。

/ Table
Schema::create('posts', function(Blueprint $table)
{
    $table->increments('id');
    $table->text('body')
    $table->integer('count');
    ...
    $table->timestamps();
});



public function show($id) 
{
    $post = Post::find($id);

    Post::update([
        'count' => $post->count + 1
    ]);


    return View::make('posts', compact('post'));
}

标签: phplaravellaravel-8

解决方案


你有两个要求:

  1. 增加每个视图的视图计数。
public function show($id) 
{
    $post = Post::find($id);

    Post::update([
        'count' => $post->count + 1
    ]);


    return View::make('posts', compact('post'));
}
  1. 根据查看次数显示查看次数最多的博客
$post = Post::orderBy('count', 'DESC')->first();
  1. 另外,要根据查看次数显示查看次数最多的博客列表,
$post = Post::orderBy('count', 'DESC')->get();

推荐阅读