Posts Learn Snippets Categories Tags About
/

Laravel Visitors Counter

Learn how to implement Laravel visitors counter and display the total number of views is visiting your content

Created on Jul 15, 2021

13 views

To implement Laravel visitor counter you can make use of a package called awssat/laravel-visits and it's very simple to implement.

1 - Install Dependency and Publish Configs
Install the dependency and then publish the necessary configuration.
composer require awssat/laravel-visits

Publish the configuration as follows.
php artisan vendor:publish --provider="Awssat\Visits\VisitsServiceProvider" --tag=config

The migration is important to use the "eloquent" engine.
php artisan vendor:publish --provider="Awssat\Visits\VisitsServiceProvider" --tag=migrations

Run the migration to migrate the "visits" table.
php artisan migrate

2 - Update Config
Update the config to use "eloquent" as the engine which otherwise it will be set to default. The benefit of using eloquent is that later on, you will be able to reference the relationship of the associated model.
# config/visits.php

'engine' => 'eloquent'

3 - Integrate Views with The Model
Now you can initialize the views to the model that you want the visitors to be counted to. Imagine you have an "Article" model and you want to count the total of user's visits, you can define it like below.
# app/Models/Article.php

class Article extends Model
{
    /**
     * Get the instance of the user visits
     *
     * @return \Awssat\Visits\Visits
     */
    public function visitsCounter()
    {
        return visits($this);
    }

    /**
     * Get the visits relation
     * 
     * @return \Illuminate\Database\Eloquent\Relations\Relation
     */
    public function visits()
    {
        return visits($this)->relation();
    }
}

4 - Increment the Views
Now that you have integrated the model with the views, you can increment each time a user visits the page by calling the "increment()" method.
# app/Http/Controllers/ArticleController.php

php artisan show(Article $article)
{
    $article->visitsCounter()->increment();

    return view('article.show', ['article' => $article]);
}

Now every time that "show" method is called the number of visitors will be incremented.

5 - Retrieve total Visitors
To get the total number of visitors and the associated data you can make use of the following methods
$article = Article::first();

visits($article)->period('day')->count();
visits($article)->period('week')->count();
visits($article)->period('month')->count();
visits($post)->countries();
visits($post)->refs();
visits($post)->operatingSystems();
visits($post)->languages();

If you are looking for more available methods, you can directly refer to the documentation for more.

Created by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.