PHPackages                             omnitaskba/laravel-model-metrics - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. omnitaskba/laravel-model-metrics

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

omnitaskba/laravel-model-metrics
================================

Easily attach time-based metrics to any Eloquent model.

v1.0.1(5mo ago)44MITPHPPHP ^8.2CI passing

Since Dec 8Pushed 5mo agoCompare

[ Source](https://github.com/omnitaskba/laravel-model-metrics)[ Packagist](https://packagist.org/packages/omnitaskba/laravel-model-metrics)[ Docs](https://github.com/omnitaskba/laravel-model-metrics)[ RSS](/packages/omnitaskba-laravel-model-metrics/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (11)Versions (4)Used By (0)

 [![Laravel Artifact Logo](art/logo.png)](art/logo.png)

 [ ![CI Status](https://github.com/omnitaskba/laravel-model-metrics/actions/workflows/ci.yml/badge.svg) ](https://github.com/omnitaskba/laravel-model-metrics/actions/workflows/ci.yml) [ ![Latest Version on Packagist](https://camo.githubusercontent.com/829ceecd36333287911819afa46845f51155439da20d422e16f8950f57898b34/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6f6d6e697461736b62612f6c61726176656c2d6d6f64656c2d6d6574726963732e7376673f7374796c653d666c61742d737175617265) ](https://packagist.org/packages/omnitaskba/laravel-model-metrics) [ ![Laravel Version](https://camo.githubusercontent.com/a4411156f5df8613bcb79d58e5bbdce9bce8a73378d7a861818b46f7d87e7dc2/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d31302e302532422d4646324432303f7374796c653d666c6174266c6f676f3d6c61726176656c) ](https://laravel.com) [ ![Total Downloads](https://camo.githubusercontent.com/7e7e530de5c5f9aa7c4b7e5cb99df1b310e43baf061a254f53d786bbfb7b26bc/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6f6d6e697461736b62612f6c61726176656c2d6d6f64656c2d6d6574726963733f7374796c653d666c61742d737175617265) ](https://packagist.org/packages/omnitaskba/laravel-model-metrics) [ ![License](https://camo.githubusercontent.com/7ea639aadc629f8a37c969581757aa6496ea0f320e61bfcbe4d59da82c2ca3e3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6f6d6e697461736b62612f6c61726176656c2d6d6f64656c2d6d6574726963733f7374796c653d666c61742d737175617265) ](https://packagist.org/packages/omnitaskba/laravel-model-metrics)

---

Laravel Model Metrics 📊
=======================

[](#laravel-model-metrics-)

A simple and non-intrusive Laravel package that enables **daily time-series metrics** and **aggregated single-value metrics** for any Eloquent model --- without adding clutter to your main tables.

Perfect for tracking **views**, **logins**, **sales**, **XP**, **streaks**, and more.

---

🚀 Features
----------

[](#-features)

- 📅 **Daily Metrics:** Store values tracked per day (`year`, `month`, `day`).
- 🧮 **Aggregated Metrics:** Store a single key-value score (e.g., current streak).
- 🏷️ Supports **Strings** or **PHP Backed Enums** for metric names.
- ⚡ **Efficient:** Uses dedicated tables and optimized SUM queries.
- 🔌 **Plug-and-Play:** Activated by a single trait.
- 🛠️ **Configurable:** Customize table names easily.

---

📦 Installation
--------------

[](#-installation)

### 1. Install via Composer

[](#1-install-via-composer)

```
composer require omnitaskba/laravel-model-metrics
```

### 2. Run Migrations

[](#2-run-migrations)

The package creates two dedicated tables: `model_metrics` and `model_aggregated_metrics`.

```
php artisan migrate
```

### 3. Add the trait to your model

[](#3-add-the-trait-to-your-model)

Apply the `HasMetrics` trait to any Eloquent model you wish to track metrics for.

```
// app/Models/User.php

use Omnitaskba\ModelMetrics\Traits\HasMetrics;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use HasMetrics;
    // ...
}
```

📚 Usage
-------

[](#-usage)

Metric names can be passed as a string ('views') or, preferably, as a `Backed Enum` (PHP 8.1+):

```
// Example Backed Enum
enum UserMetric: string {
    case VIEWS = 'views';
    case SALES = 'sales';
    case STREAK = 'streak';
    case HIGH_SCORE = 'high_score';
    // ...
}
```

Daily &amp; Aggregated Metrics Documentation
--------------------------------------------

[](#daily--aggregated-metrics-documentation)

### 📅 Daily Metrics (Time Series)

[](#-daily-metrics-time-series)

Daily metrics are stored by day (year, month, day) and track historical, time‑sensitive data.

---

#### 1. `incrementDailyMetric()`

[](#1-incrementdailymetric)

Increments the metric value for the current day. Creates the daily record if it doesn't exist.

ArgumentTypeDefaultDescription`name`string or BackedEnumRequiredThe name of the metric (e.g., `UserMetric::HIGH_SCORE`).`value`float1.0Amount to increment by.##### Example

[](#example)

```
// Assuming current date is 2025-12-09
$user->incrementDailyMetric(UserMetric::HIGH_SCORE);       // Value: 1.0
$user->incrementDailyMetric(UserMetric::HIGH_SCORE, 5.5);  // Value: 6.5
```

**Returns:** New value of the metric record.

---

#### 2. `decrementDailyMetric()`

[](#2-decrementdailymetric)

Decrements the metric value for the current day. Creates the daily record if it doesn't exist.

ArgumentTypeDefaultDescription`name`string or BackedEnumRequiredThe metric name.`value`float1.0Amount to decrement by.##### Example

[](#example-1)

```
// Assuming current daily high_score are 20.0
$user->decrementDailyMetric(UserMetric::HIGH_SCORE, 0.5);
```

**Returns:** New value (`19.5` in this case).

---

#### 3. `getTodayMetric()`

[](#3-gettodaymetric)

Retrieves today's metric value.

ArgumentTypeDefaultDescription`name`string or BackedEnumRequiredMetric name.##### Example

[](#example-2)

```
$todayViews = $user->getTodayMetric(UserMetric::HIGH_SCORE);
```

**Returns:**
`float(19.5)` --- or `0.0` if none exists.

---

#### 4. `getTotalMetric()`

[](#4-gettotalmetric)

Calculates the sum across all days between two dates (inclusive).

ArgumentTypeDefaultDescription`name`string or BackedEnumRequiredMetric name.`startDate`DateTimeInterfacenullStart date.`endDate`DateTimeInterfacenullEnd date.##### Example

[](#example-3)

```
use DateTime;

$start = new DateTime('2025-10-01');
$end = new DateTime('2025-10-31');

$totalSales = $user->getTotalMetric(ProductMetric::SALES, $start, $end);
```

**Returns:** `float(1250.0)` or `0.0` if no data.

---

#### 5. `getTotalForPastDays()`

[](#5-gettotalforpastdays)

Sums the metric for the last N days (including today).

ArgumentTypeDefaultDescription`name`string or BackedEnumRequiredMetric name.`days`intRequiredHow many days to look back.##### Example

[](#example-4)

```
$lastWeekViews = $user->getTotalForPastDays(ProductMetric::VIEWS, 7);
```

**Returns:** `float(85.5)`

---

#### 6. `getMetricHistory()`

[](#6-getmetrichistory)

Retrieves a collection of daily metric records grouped by day, sorted descending.

ArgumentTypeDefaultDescription`name`string or BackedEnumRequiredMetric name.`limit`int30Max number of records.##### Example

[](#example-5)

```
$history = $user->getMetricHistory(ProductMetric::VIEWS, 10);
```

---

### 📊 Aggregated Metrics (Single Value)

[](#-aggregated-metrics-single-value)

Aggregated metrics store a single persistent value.

---

#### 1. `setAggregatedMetric()`

[](#1-setaggregatedmetric)

Sets or overwrites the metric value.

ArgumentTypeDefaultDescription`name`string or BackedEnumRequiredMetric name.`value`floatRequiredValue to set.##### Example

[](#example-6)

```
$user->setAggregatedMetric(UserMetric::HIGH_SCORE, 999.5);
```

---

#### 2. `incrementAggregatedMetric()`

[](#2-incrementaggregatedmetric)

Increases the metric value.

ArgumentTypeDefaultDescription`name`string or BackedEnumRequiredMetric name.`value`float1.0Increment amount.##### Example

[](#example-7)

```
$user->incrementAggregatedMetric(UserMetric::LOGIN_STREAK); // New value: 6.0
```

---

#### 3. `decrementAggregatedMetric()`

[](#3-decrementaggregatedmetric)

Decreases the value.

ArgumentTypeDefaultDescription`name`string or BackedEnumRequiredMetric name.`value`float1.0Decrement amount.##### Example

[](#example-8)

```
$user->decrementAggregatedMetric(UserMetric::HIGH_SCORE, 5.5); // New value: 94.5
```

---

#### 4. `getAggregatedMetric()`

[](#4-getaggregatedmetric)

Retrieves current aggregated value.

##### Example

[](#example-9)

```
$currentScore = $user->getAggregatedMetric(UserMetric::HIGH_SCORE);
```

**Returns:** `float(999.5)` (or `0.0` if missing)

---

#### 5. `hasAggregatedMetric()`

[](#5-hasaggregatedmetric)

Checks if the record exists.

##### Example

[](#example-10)

```
if ($user->hasAggregatedMetric(UserMetric::HIGH_SCORE)) {
    // ...
}
```

---

#### 6. `resetAggregatedMetric()`

[](#6-resetaggregatedmetric)

Sets value to `0.0` (record stays).

##### Example

[](#example-11)

```
$user->resetAggregatedMetric(UserMetric::LOGIN_STREAK);
```

---

#### 7. `clearAggregatedMetric()`

[](#7-clearaggregatedmetric)

Deletes the aggregated metric record entirely.

##### Example

[](#example-12)

```
$user->clearAggregatedMetric('old_metric');
```

**Returns:** `true` on success, `false` if not found.

⚙️ Configuration
----------------

[](#️-configuration)

You can publish the configuration file to customize the table names used by the package:

```
php artisan vendor:publish --tag=model-metrics-config
```

This will create a config/model-metrics.php file with the following contents, allowing you to customize the table names and model classes used for each metric type:

```
// config/model-metrics.php
return [
    'time_series' => [
        'table_name' => 'model_metrics',
        'model' => \Omnitaskba\ModelMetrics\Models\Metric::class,
    ],

    'aggregated' => [
        'table_name' => 'model_aggregated_metrics',
        'model' => \Omnitaskba\ModelMetrics\Models\AggregatedMetric::class,
    ],
];
```

**Key Configuration Options:**

- `time_series.table_name`: The table used for Daily Metrics (Time Series).
- `aggregated.table_name`: The table used for Aggregated Metrics (Single Value).

🔧 Performance Notes
-------------------

[](#-performance-notes)

- Indexes: The underlying tables (metrics and aggregated\_metrics) are indexed on the required columns (name, model\_id, model\_type, and date columns) to ensure rapid retrieval and SUM operations.
- Unique Constraints: Daily metrics use a unique constraint on (name, year, month, day, model\_id, model\_type) to prevent duplicate entries and ensure atomic updates.

🧪 Testing
---------

[](#-testing)

You can run the full test suite with:

```
composer test
```

🤝 Contributing
--------------

[](#-contributing)

See **CONTRIBUTING.md**.

📄 Changelog
-----------

[](#-changelog)

Please see **CHANGELOG.md** for more information what has changed recently.

🔐 Security
----------

[](#-security)

If you discover any security related issues, please email  instead of using the issue tracker.

💡 Credits
---------

[](#-credits)

- [Zlatan Goralija](https://github.com/zlatangoralija)

📄 License
---------

[](#-license)

Laravel Model Metrics is open-sourced software licensed under the MIT License.

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance73

Regular maintenance activity

Popularity7

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

3

Last Release

154d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/4bcbf1f65116a4efd4ca62a1a2d657b0f221749051964a53674f38898ddab017?d=identicon)[zlatangoralija](/maintainers/zlatangoralija)

---

Top Contributors

[![zlatangoralija](https://avatars.githubusercontent.com/u/36918435?v=4)](https://github.com/zlatangoralija "zlatangoralija (17 commits)")

---

Tags

laravelMetricsanalyticsomnitaskba

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/omnitaskba-laravel-model-metrics/health.svg)

```
[![Health](https://phpackages.com/badges/omnitaskba-laravel-model-metrics/health.svg)](https://phpackages.com/packages/omnitaskba-laravel-model-metrics)
```

###  Alternatives

[barryvdh/laravel-ide-helper

Laravel IDE Helper, generates correct PHPDocs for all Facade classes, to improve auto-completion.

14.9k123.0M687](/packages/barryvdh-laravel-ide-helper)[bezhansalleh/filament-google-analytics

Google Analytics integration for FilamentPHP

205144.8k5](/packages/bezhansalleh-filament-google-analytics)[glhd/special

1929.4k](/packages/glhd-special)[bjuppa/laravel-blog

Add blog functionality to your Laravel project

483.3k2](/packages/bjuppa-laravel-blog)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
