Laravel visitors counter

后端 未结 4 1621
情书的邮戳
情书的邮戳 2020-12-29 13:34

I\'m trying to build a visitors counter in Laravel....

I don\'t know what the best place is to put the code inside so that it loads on EVERY page... But I putted it

4条回答
  •  鱼传尺愫
    2020-12-29 13:50

    Looking at your code and reading your description, I’m assuming you want to calculate number of hits from an IP address per day. You could do this using Eloquent’s updateOrNew() method:

    $ip = Request::getClientIp();
    $visit_date = Carbon::now()->toDateString();
    
    $visitor = Visitor::findOrNew(compact('ip', 'visit_date'));
    $visitor->increment('hits');
    

    However, I would add this to a queue so you’re not hitting the database on every request and incrementing your hit count can be done via a background process:

    Queue::push('RecordVisit', compact('ip', 'visit_date'));
    

    In terms of where to bootstrap this, the App::before() filter sounds like a good candidate:

    App::before(function($request)
    {
        $ip = $request->getClientIp();
        $visit_date = Carbon::now()->toDateString();
    
        Queue::push('RecordVisit', compact('ip', 'visit_date'));
    );
    

    You could go one step further by listening for this event in a service provider and firing your queue job there, so that your visit counter is its own self-contained component and can be added or removed easily from this and any other projects.

提交回复
热议问题