Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
E

eloquent-viewable

> 后端框架
Open source

A minimalistic analytics package for Laravel with seamless view tracking for Eloquent models

885 stars0 likes3 views
WebsiteGitHub

About

A minimalistic analytics package for Laravel with seamless view tracking for Eloquent models

Table of Contents

Introduction

Getting Started

Version Compatibility

Installation

Usage

Preparing your model

Recording views

Queueing view recording

Setting a cooldown

Retrieving view counts

Get total view count

Get view count for a specific period

Get unique view count

Ordering models by view count

Order by view count

Order by unique view count

Order by view count within the specified period

Order by view count within the specified collection

Get view count of viewable type

View collections

Remove views on delete

Caching view counts

Optimizing

Database indexes

Caching

Extending

Custom information about visitor

Using your own Views Eloquent model

Using your own View Eloquent model

Customizing how views are created

Using a custom crawler detector

Adding macros to the Views class

Upgrading

Changelog

Contributing

Credits

Introduction

Eloquent Viewable is a flexible and minimalistic analytics package for Laravel that allows seamless tracking of views for Eloquent models. Rather than incrementing a single counter, it stores each view as its own database record, so you can analyze totals, unique visitors, and custom time periods entirely within your own application. Whether you're running a blog, an e-commerce store, or a custom Laravel application, this package lets you log and analyze views without relying on external analytics services.

Quick Example

Once installed, you can track and retrieve views effortlessly:

php
// Return total view count
views($post)->count();

// Return total unique view count since 20 February 2017
views($post)->unique()->period(Period::since('2017-02-20'))->count();

// Record a view
views($post)->record();

Key Features

  • Track total and unique views for any Eloquent model
  • Query views by custom date ranges or time periods
  • Prevent duplicate views with a configurable cooldown system
  • Order models by views and unique visitors
  • Optimize performance with built-in caching
  • Ignore views from crawlers, blocked IPs, and DNT users

Getting Started

Version Compatibility

Package Version Laravel PHP
8.x 13.x 8.5+
7.x 6.x – 13.x 7.4+

Support for Lumen is not maintained.

Installation

First, you need to install the package via Composer:

bash
composer require cyrildewit/eloquent-viewable:^8

Publish the database migrations and review them:

bash
php artisan vendor:publish --provider="CyrildeWit\EloquentViewable\EloquentViewableServiceProvider" --tag="migrations"

Run the database migrations to create the necessary tables:

bash
php artisan migrate

You can optionally publish the config file:

bash
php artisan vendor:publish --provider="CyrildeWit\EloquentViewable\EloquentViewableServiceProvider" --tag="config"

Usage

Preparing your model

To associate views with a model, the model must implement the following interface and trait:

  • Interface: CyrildeWit\EloquentViewable\Contracts\Viewable
  • Trait: CyrildeWit\EloquentViewable\InteractsWithViews

Example:

php
use Illuminate\Database\Eloquent\Model;
use CyrildeWit\EloquentViewable\InteractsWithViews;
use CyrildeWit\EloquentViewable\Contracts\Viewable;

class Post extends Model implements Viewable
{
    use InteractsWithViews;

    // ...
}

Recording views

To track a view, simply call the record method on the fluent Views instance:

php
views($post)->record();

Where Should You Record Views?

The recommended place to record views is inside your controller’s method that handles displaying the model. For example:

php
// PostController.php
public function show(Post $post)
{
    views($post)->record();

    return view('post.show', compact('post'));
}

This ensures that views are only recorded when the page is actually rendered for a user.

[!WARNING]
By default, this package automatically ignores views from crawlers to prevent inaccurate counts. Keep this in mind when testing—tools like Postman are often detected as crawlers and will not trigger a recorded view.

Queueing view recording

By default, views are stored during the request. On high-traffic pages you can defer the database write to a queued job instead. This keeps the request fast and moves the insert to a queue worker.

Queue an individual view on the fly using the queue() method:

php
views($post)->queue()->record();

Or enable queueing globally in the eloquent-viewable.php config file:

php
'queue' => [
    'enabled' => true,      // queue every recorded view
    'connection' => null,   // null uses the default queue connection
    'queue' => null,        // null uses the connection's default queue
],

When queueing is enabled globally, you can still force an individual view to be recorded synchronously:

php
views($post)->queue(false)->record();

All filtering still runs during the request, including crawler detection, the Do Not Track header, ignored IP addresses and cooldowns. Bots and views on cooldown are therefore never queued; only the database write is deferred.

[!WARNING]
When a view is queued, the ViewRecorded event is dispatched from the queue worker instead of the request. Its listeners therefore run without request context. The session, cookies, request() and auth()->user() are unavailable and will return empty or null values. If a listener needs request-derived data (such as the authenticated user or the IP address), capture it during the request instead of reading it inside the listener.

Setting a cooldown

You may use the cooldown method on the Views instance to add a cooldown between view records. When you set a cooldown, you need to specify the number of minutes.

php
views($post)
    ->cooldown($minutes)
    ->record();

Instead of passing the number of minutes as an integer, you can also pass a DateTimeInterface instance.

php
$expiresAt = now()->addHours(3);

views($post)
    ->cooldown($expiresAt)
    ->record();

How it works

When recording a view with a session delay, this package also saves a snapshot of the view in the visitor’s session with an expiration datetime. Whenever the visitor views the item again, the package checks their session and decides whether the view should be saved in the database.

Retrieving view counts

Get total view count

php
views($post)->count();

Get view count for a specific period

php
use CyrildeWit\EloquentViewable\Support\Period;

// Example: get view count from 2017 up to 2018
views($post)
    ->period(Period::create('2017', '2018'))
    ->count();

The Period class that comes with this package provides many handy features. The API of the Period class looks as follows:

Specifying a date range
php
$startDateTime = Carbon::createFromDate(2017, 4, 12);
$endDateTime = '2017-06-12';

Period::create($startDateTime, $endDateTime);
Since a specific date
php
Period::since(Carbon::create(2017));
Up to a specific date
php
Period::upto(Carbon::createFromDate(2018, 6, 1));
For past period

Uses Carbon::today() as start datetime minus the given unit.

php
Period::pastDays(int $days);
Period::pastWeeks(int $weeks);
Period::pastMonths(int $months);
Period::pastYears(int $years);
For custom time subtraction

Uses Carbon::now() as start datetime minus the given unit.

php
Period::subSeconds(int $seconds);
Period::subMinutes(int $minutes);
Period::subHours(int $hours);
Period::subDays(int $days);
Period::subWeeks(int $weeks);
Period::subMonths(int $months);
Period::subYears(int $years);

Get unique view count

If you only want to retrieve the unique view count, you can simply add the unique method to the chain.

php
views($post)
    ->unique()
    ->count();

Ordering models by view count

The Viewable trait adds two scopes to your model: orderByViews and orderByUniqueViews.

Order by view count

php
Post::orderByViews()->get(); // descending
Post::orderByViews('asc')->get(); // ascending

Order by unique view count

php
Post::orderByUniqueViews()->get(); // descending
Post::orderByUniqueViews('asc')->get(); // ascending

Order by view count within the specified period

php
Post::orderByViews('asc', Period::pastDays(3))->get();  // ascending
Post::orderByViews('desc', Period::pastDays(3))->get(); // descending

And of course, it's also possible with the unique views variant:

php
Post::orderByUniqueViews('asc', Period::pastDays(3))->get();  // ascending
Post::orderByUniqueViews('desc', Period::pastDays(3))->get(); // descending

Order by view count within the specified collection

php
Post::orderByViews('asc', null, 'custom-collection')->get();  // ascending
Post::orderByViews('desc', null, 'custom-collection')->get(); // descending

Post::orderByUniqueViews('asc', null, 'custom-collection')->get();  // ascending
Post::orderByUniqueViews('desc', null, 'custom-collection')->get(); // descending

Get view count of viewable type

If you want to know how many views a specific viewable type has, you need to pass an empty Eloquent model to the views() helper like so:

php
views(new Post())->count();

You can also pass a fully qualified class name. The package will then resolve an instance from the application container.

php
views(Post::class)->count();
views('App\Post')->count();

View collections

If you have different types of views for the same viewable type, you may want to store them in their own collection.

php
views($post)
    ->collection('customCollection')
    ->record();

To retrieve the view count in a specific collection, you can reuse the same collection() method.

php
views($post)
    ->collection('customCollection')
    ->count();

Remove views on delete

To automatically delete all views associated with a viewable Eloquent model when it is deleted, set the removeViewsOnDelete property to true in your model definition.

php
protected $removeViewsOnDelete = true;

Caching view counts

Caching the view count can be challenging in some scenarios. The period can be for example dynamic which makes caching not possible. That's why you can make use of the in-built caching functionality.

To cache the view count, simply add the remember() method to the chain. The default lifetime is forever.

Examples:

php
views($post)->remember()->count();
views($post)->period(Period::create('2018-01-24', '2018-05-22'))->remember()->count();
views($post)->period(Period::upto('2018-11-10'))->unique()->remember()->count();
views($post)->period(Period::pastMonths(2))->remember()->count();
views($post)->period(Period::subHours(6))->remember()->count();
php
// Cache for 3600 seconds
views($post)->remember(3600)->count();

// Cache until the defined DateTime
views($post)->remember(now()->addWeeks(2))->count();

// Cache forever
views($post)->remember()->count();

Optimizing

Storing every view as its own record is what makes detailed, time-bas

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPanalyticseloquenteloquent-ormlaravel

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架