-3

im using laravel middleware (visits) to create visits record in database like this:

public function handle(Request $request, Closure $next)
{

    Visit::create([
        'ip' => 'user ip',
        'browser' => 'user browser',
        'url' => url()->current(),
        'referer' => $request->headers->get('referer'),
    ]);


    return $next($request);
}

the problem is here: If the user refreshes the page quickly, a large number of records will be saved

what can i do to prevent this?

K1-Aria
  • 1,093
  • 4
  • 21
  • 34
  • *"a large number of records will be saved"* - 1) throttle the request; 2) put a flag on session that user has already visited that url recently. that being said, your code might bogged down if you have a fairly large visitor. people sold analytics solution to alleviate developer's headache. – Bagus Tesa Apr 24 '22 at 09:43

1 Answers1

1

You could create a unique job with some of the parameters that saves the Visit instead of directly saving it, that should work.

John Zwarthoed
  • 1,239
  • 7
  • 12
  • yes, its working. but with database queue i think it would be a heavy operation. what is your opinion about doing this by sessions?? – K1-Aria Apr 24 '22 at 14:34
  • By session is a different approach, but not sure if its really reliable, because if you have multiple consecutive request by holding ctrl-r then the session doesn’t know you have visited the page – John Zwarthoed Apr 25 '22 at 16:26