Basic Usage

Use HasVisits Trait

The first thing you need to do is, to use HasVisits trait, and implement CanVisit interface.

1namespace App\Models\Post;
2 
3use Coderflex\Laravisit\Concerns\CanVisit;
4use Coderflex\Laravisit\Concerns\HasVisits;
5use Illuminate\Database\Eloquent\Factories\HasFactory;
6use Illuminate\Database\Eloquent\Model;
7 
8class Post extends Model implements CanVisit
9{
10 ...
11 use HasFactory;
12 use HasVisits;
13 ...
14}

After this step, you are all set, you can now count visits by using visit method

1$post->visit();

You can chain methods to the visit method. Here are a list of the available methods:

METHOD SYNTAX DESCRIPTION EXAMPLE
withIp() string $ip = null Set an Ip address (default request()->ip()) $post->visit()->withIp()
withSession() string $session = null Set an Session ID (default session()->getId()) $post->visit()->withSession()
withData() array $data Set custom data $post->visit()->withData(['region' => 'USA'])
withUser() Model $user = null Set a user model (default auth()->user()) $user->visit()->withUser()

By default, you will have unique visits each day using dailyInterval() method. Meaning, when the users access the page multiple times in a day time frame, you will see just one record related to them.

If you want to log users access to a page with different timeframes, here are a bunch of useful methods:

METHOD SYNTAX DESCRIPTION EXAMPLE
hourlyInterval() void Log visits each hour $post->visit()->hourlyIntervals()->withIp();
dailylyInterval() void Log visits each day $post->visit()->dailylyIntervals()->withIp();
weeklyInterval() void Log visits each week $post->visit()->weeklyIntervals()->withIp();
monthlyInterval() void Log visits each month $post->visit()->monthlyIntervals()->withIp();
yearlyInterval() void Log visits each year $post->visit()->yearlyIntervals()->withIp();
customInterval() mixed $interval Log visits within a custom interval $post->visit()->customInterval( now()->subYear() )->withIp();

Join our newsletter

Subscribe to Our Newsletter and never miss our offers, latest news, Articles, etc.

We care about the protection of your data. Read our Privacy Policy.