Counting page views with Laravel

前端 未结 5 850
北荒
北荒 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:25

    First of all thanks to user33192 for sharing the eloquent viewable. Just want to make it clearer for others after looking at the docs. Look at the docs to install the package.

    Do this in your Post Model:

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

    In your posts controller, use the record method to save a view;

    public function show($slug)
    {
        $post = Post::where('slug',$slug)->first();
        views($post)->record();
        return view('posts.show',compact('post'));
    }
    

    In your views you can return the views (mine is posts.show) as you want. Check the document for more. I will just the total views of a post.

    
    

提交回复
热议问题