Brian Le
Brian Le

Reputation: 9

Laravel visitor counter?

I'm a newbie. I have been coding my website for 2 weeks, and now the job is going to be finished, But I don't know how to make a simple Visitor Counter. I consider using Session to do that. Please help me to make a simple visitor counter.

Upvotes: 0

Views: 4151

Answers (2)

duy nguyen
duy nguyen

Reputation: 79

-I think you should make a table called "visitors" include 3 column: ip, visited_date, hits.

-After each request to your website you save information to visitors table:

$ip = Request::getClientIp();
$visited_date = Date("Y-m-d:H:i:s");
$vistor = Visitor::firstOrCreate(['ip' => $ip], 'visited_date' => $visited_date]);
$vistor->increment('hits');

Upvotes: 2

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

The simplest way to do that is to keep visitor counter in a table and increment it with each request. If you want to count visits per user, you could do something like this:

auth()->user()->increment('number_of_visits')

If you need to save more data, just create a new record for each request. For example:

Visit::create(['ip' => $request->ip(), 'user_id' => auth()->id()])

Upvotes: 4

Related Questions