Counting page views with Laravel

前端 未结 5 911
北荒
北荒 2021-02-01 10:02

I want to implement page view counter in my app. What I\'ve done so far is using this method :

public function showpost($titleslug) {
        $post = Post::where         


        
5条回答
  •  不要未来只要你来
    2021-02-01 10:11

    Eloquent Viewable package can be used for this purpose. It provides more flexible ways to do stuff like this(counting page views).

    Note:The Eloquent Viewable package requires PHP 7+ and Laravel 5.5+.

    Make Model viewable:

    Just add the Viewable trait to the model definition like:

    use Illuminate\Database\Eloquent\Model;
    use CyrildeWit\EloquentViewable\Viewable;
    
    class Post extends Model
    {
        use Viewable;
    
        // ...
    }
    

    Then in the controller:

    public function show(Post $post)
    {
        $post->addView();
    
        return view('blog.post', compact('post'));
    }
    

    After that you can do stuff like this:(see package installation guide for more details)

    // Get the total number of views
    $post->getViews();
    
    // Get the total number of views since the given date
    $post->getViews(Period::since(Carbon::parse('2014-02-23 00:00:00')));
    
    // Get the total number of views between the given date range
    $post->getViews(Period::create(Carbon::parse('2014-00-00 00:00:00'), Carbon::parse('2016-00-00 00:00:00')));
    
    // Get the total number of views in the past 6 weeks (from today)
    $post->getViews(Period::pastWeeks(6));
    
    // Get the total number of views in the past 2 hours (from now)
    $post->getViews(Period::subHours(2));
    
    // Store a new view in the database
    $post->addView();
    

    Implements same kind of idea as in the accepted answer, but provides more features and flexibilities.

提交回复
热议问题