Count web visits in laravel/ php

Active3 hr before
Viewed126 times

8 Answers


i added the following code to the web.php file above all the routes to run on each request on the site so no matter what page the visitor landed on it will save the ip addess to the database only if its unique so one visitor wont keep addding to the visitor count,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.,In laravel 5.7 it required parent::boot() otherwise it will show Undefined index: App\Tracker,Change the visit_date (datetime) column into visit_date (date) and visit_time (time) columns, then create an id column to be the primary key. Lastly, set ip + date to be a unique key to ensure you can't have the same IP entered twice for one day.

This is just for ease: make an Eloquent model for the table so you don't have to use Fluent (query builder) all the time:

class Tracker extends Eloquent {

   public $attributes = ['hits' => 0];

   protected $fillable = ['ip', 'date'];
   protected $table = 'table_name';

   public static
   function boot() {
      // Any time the instance is updated (but not created)
      static::saving(function($tracker) {
         $tracker - > visit_time = date('H:i:s');
         $tracker - > hits++;

   public static
   function hit() {
         'ip' => $_SERVER['REMOTE_ADDR'],
         'date' => date('Y-m-d'),
      ]) - > save();


Now you should be able to do what you want by just calling this:

load more v

Of course, the middleware also needs to be registered in app/Http/Kernel as a route middleware. I've registered it like this:,These are more or less the biggest advantages and disadvantages of using this approach.,The concept of this approach to visitor tracking is fairly simple. The goal is to have an anonymized record of unique visits of our website for each day. I'm going to show an example of this in Laravel, but this concept can be taken to other frameworks and languages. I've tested this in regular PHP, it can be also done in .NET or Python (with some modifications of course).,For this article, I'm not going to go into detail about visualizing the data we've collected as that could be a whole separate article. I'm just going to leave a link to a GitHub gist containing the code needed to visualize the data. The final result can be seen below.

As simple as the concept was, the execution is keeping it simple as well. For this to work, we are going to need to write a custom middleware which determines if a visitor has already been recorded for a given day. If the visitor hasn't been recorded, it will insert their visit into the database, otherwise, the visit will not be registered. The middleware checks the visitor's IP hash against the hash in the database to determine if the visit had been recorded before. Now let's look at the code of this middleware:

// app/Http/Middleware/CountVisitor.php

? php

namespace App\ Http\ Middleware;

use Closure;
use Illuminate\ Http\ Request;
use App\ Models\ Visitor;

class CountVisitor {
    * Handle an incoming request.
    * @param  \Illuminate\Http\Request  $request
    * @param  \Closure  $next
    * @return mixed
   function handle(Request $request, Closure $next) {
      $ip = hash('sha512', $request - > ip());
      if (Visitor::where('date', today()) - > where('ip', $ip) - > count() < 1) {
            'date' => today(),
            'ip' => $ip,
      return $next($request);
load more v

Anonymized Website Visitor Counter in Laravel Application , Learn how to anonymously count your visitor visit on your page and display the stats to the public , How to implement Laravel visitor views / visitor counter , How to implement Json Feed in Laravel

composer require cyrildewit / eloquent - viewable
load more v

Laravel Page Visits Counter is a powerful, flexible and lightweight Laravel package for adding a page view counter to your Eloquent models. It's designed to be flexible and useful for various projects. Instead of only a simple visits counter we provide out of the box some great functionalities.,First add the Cyrildewit\PageVisitsCounter\Traits\HasPageVisitsCounter trait to your visitable Eloquent model(s).,Usage Making a Elqouent model visitable Retrieving page visits count Storing new visits ,This package allows you to store page visits of different models into the database.

load more v

Laravel Visits is a package by Bader Almutairi for attaching counters to any model to track visits with tags. The main features this package provides, include the following:,To view the full readme, including installation instructions and source code, check this package out on the GitHub repo awssat/laravel-visits. Great work Bader!,You can integrate this package directly into your Eloquent model by defining a method like visits:,You can also collect other interesting data about country and referrer if you want a quick analytics tool for tracking models:

The basic usage for counting models includes the following methods for incrementing and decrementing among others:

 1 visits($post) - > increment();
 2 3 // More than one 4visits($post)->increment(10); 5 6visits($post)->decrement(); 7 8// More than one 9visits($post)->decrement(10);1011// Only increment once every 30 seconds based on user's IP12visits($post)->seconds(30)->increment()
load more v

If you are using Redis as your default data engine, skip this.,Publish migration file, then migrate,If you are not using Redis as your default data engine, skip this.,To prevent any data loss add a new connection in config/database.php

To get started with Laravel Visits, use Composer to add the package to your project’s dependencies:

composer require awssat / laravel - visits
load more v

I want to collect the unique amount of visitors on my website and store them in a database. Even when someone without an account accesses the website the visitor count goes up. How can I accomplish this?,The Questions I've linked to in my response comment go into greater detail but to sum it up, you can use an inline function or the at() method to deal with multiple cases.,I know I have to fetch the users IP address or something along those lines but I don't know how to fetch the IP address of a user without an account when the page loads,You might want to explore creating an empty request and filling it with data if that is possible in your use case as that'll let you run your unit test with more ease and less issues. This won't work in all cases.

Currently I have this DB table

   ip -


Route::get('/', function() {
   $ip = Request::ip();
   return view('welcome', compact('ip'));
load more v

If a user visits a page or post then our Database field name view_count is automatically incremented. In this tutorial, we will see how we can create a site visitor counter laravel. Laravel page view counter will be the tutorial today.,Today we are going to know how to implement Postor Page views count using Laravel . We can say it is going to be click counter or single post visitor counter. We will create this traffic counter using Laravel. ,So let's see how we can implement how to count a single post view in Laravel 8. We can do it using cyrildewit laravel page view counter package. But in this tutorial, I don't use any packages. I will do it using our own code., The Substitution of Laravel Chunk to Process Big Data Example Handle Query String Pagination with withQueryString Helper in Laravel How to ReFactor Default Query Scope in Laravel Change Column Name and Type Without Losing Data in Laravel How to Set and Get Session Example in Laravel


class PostController extends Controller {
   function post(post $post) {
      $Key = 'blog'.$post - > id;
      if (\Session::has($Key)) {

         DB::table('posts') -
            > where('id', $post - > id) -
            > increment('view_count', 1);\
         Session::put($Key, 1);

      // Write your code which you want
load more v

Other "count-undefined" queries related to "Count web visits in laravel/ php"