PHPackages                             our-education/laravel-request-tracker - 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. [HTTP &amp; Networking](/categories/http)
4. /
5. our-education/laravel-request-tracker

ActiveLibrary[HTTP &amp; Networking](/categories/http)

our-education/laravel-request-tracker
=====================================

Event-driven Laravel package for tracking user access patterns with daily summaries, detailed journeys, and module-level analytics

2.3.2(5mo ago)0157MITPHPPHP ^8.0

Since Nov 12Pushed 5mo ago2 watchersCompare

[ Source](https://github.com/our-edu/laravel-request-tracker)[ Packagist](https://packagist.org/packages/our-education/laravel-request-tracker)[ Docs](https://github.com/our-edu/laravel-request-tracker)[ RSS](/packages/our-education-laravel-request-tracker/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (2)Versions (28)Used By (0)

Laravel Request Tracker
=======================

[](#laravel-request-tracker)

Event-driven Laravel package for tracking user access patterns with **daily summaries**, **detailed journeys**, and **module-level analytics**. Automatically logs user activity in background jobs without slowing down your application.

Features
--------

[](#features)

✅ **Daily Activity Summary** - One record per user+role+date with access count &amp; timestamps
✅ **Detailed User Journey** - Track unique endpoints with module/submodule organization
✅ **PHP 8 Attributes** - Use `#[TrackModule('module', 'submodule')]` on controllers
✅ **Auto Module Detection** - Fallback to pattern matching when no attribute provided
✅ **Queue-Based** - All tracking via background jobs (respects `QUEUE_CONNECTION`)
✅ **National ID Support** - Commands filter by national\_id for easier access
✅ **Role Name Storage** - Store role names from `roles.name` for filtering
✅ **Silent Errors** - Tracking failures won't break your application
✅ **Data Retention** - Automatic cleanup of old records

---

Quick Start
-----------

[](#quick-start)

```
# Install
composer require our-education/laravel-request-tracker

# Publish & migrate
php artisan vendor:publish --provider="OurEdu\RequestTracker\RequestTrackerServiceProvider"
php artisan migrate

# Enable in .env
REQUEST_TRACKER_ENABLED=true
QUEUE_CONNECTION=redis

# Start queue worker
php artisan queue:work
```

**Add to controllers:**

```
use OurEdu\RequestTracker\Attributes\TrackModule;

#[TrackModule('orders')]
class OrderController extends Controller {
    // All methods tracked as 'orders' module
}

#[TrackModule('users', 'profile')]
class ProfileController extends Controller {
    // Tracked as 'users.profile' (module.submodule)
}
```

**View reports:**

```
php artisan tracker:user-stats 1234567890
php artisan tracker:user-journey 1234567890 --date=2025-01-15
php artisan tracker:module-access orders --from=2025-01-01
```

---

How It Works
------------

[](#how-it-works)

**Architecture:** `Request` → `RequestHandled Event` → `EventsSubscriber` → `TrackUserAccessJob` (queue) → `Database`

1. After a request completes (post-auth middleware), `RequestHandled` event fires
2. `EventsSubscriber` extracts user, role info and dispatches job to queue
3. `TrackUserAccessJob` processes in background:
    - Creates/updates daily summary in `request_trackers` table
    - Checks for `#[TrackModule]` attribute on controller (priority 1)
    - If no attribute, falls back to auto-detection via ModuleExtractor
    - Creates detailed record in `user_access_details` table if module detected
4. Your application responds immediately (no blocking)

**What's Tracked:**

- **Daily Summary** (all requests): User+role+date, access count, timestamps
- **Detailed Journey** (when module detected): Endpoint, module, submodule, action, visit count

---

Configuration
-------------

[](#configuration)

**Environment Variables:**

```
REQUEST_TRACKER_ENABLED=true              # Enable/disable tracking
REQUEST_TRACKER_SILENT_ERRORS=true        # Don't break app on errors
REQUEST_TRACKER_AUTO_CLEANUP=false        # Auto-delete old records
REQUEST_TRACKER_QUEUE_NAME=tracking       # Queue name (null = default)
```

**Config File** (`config/request-tracker.php`):

```
return [
    'enabled' => env('REQUEST_TRACKER_ENABLED', false),
    'silent_errors' => env('REQUEST_TRACKER_SILENT_ERRORS', true),

    // Exclude paths from tracking
    'exclude' => [
        'parent/look-up',         // Suffix match
        'api/*/internal',         // Wildcard
        'regex:/^health/',        // Regex
    ],

    // Auth guards to check
    'auth_guards' => ['web', 'api'],

    // Queue configuration
    'queue' => [
        'queue' => env('REQUEST_TRACKER_QUEUE_NAME', null), // null = default
    ],

    // Data retention
    'retention' => [
        'auto_cleanup' => env('REQUEST_TRACKER_AUTO_CLEANUP', false),
        'keep_summaries_days' => 90,
        'keep_detailed_days' => 30,
    ],

    // Module auto-extraction from URLs
    'module_mapping' => [
        'enabled' => true,

        // Pattern matching (checked first)
        'patterns' => [
            '/admission/' => 'admission',
            '/subject/' => 'subjects',
            '/certificate_manager/' => 'subjects',
            '/users/' => 'users',
            '/auth/' => 'authentication',
        ],

        // Auto-extract from path segments (fallback)
        // e.g., 'api/v1/en/subject/list' -> 'subject' (segment 3)
        'auto_extract' => true,
        'auto_extract_segment' => 3, // 0-based index after api/v1/locale
    ],
];
```

---

Usage
-----

[](#usage)

### 1. Add Attributes to Controllers

[](#1-add-attributes-to-controllers)

```
use OurEdu\RequestTracker\Attributes\TrackModule;

// Simple module
#[TrackModule('orders')]
class OrderController extends Controller {
    public function index() { /* module='orders', action='index' */ }
    public function show($id) { /* module='orders', action='show' */ }
}

// Module + Submodule
#[TrackModule('users', 'profile')]
class ProfileController extends Controller {
    public function show($id) { /* module='users', submodule='profile' */ }
}

// Multiple controllers, same parent module
#[TrackModule('reports', 'sales')]
class SalesReportController { }

#[TrackModule('reports', 'inventory')]
class InventoryReportController { }
```

**Action derivation:** Route name last segment (e.g., `users.profile.show` → `show`) or method name.

**Without attribute:** Daily summary still tracked, but no detailed journey records.

### 2. Query the Data

[](#2-query-the-data)

```
use OurEdu\RequestTracker\Models\{RequestTracker, UserAccessDetail};

// Get today's summary
$summary = RequestTracker::forUser($userUuid)->today()->first();

// Get user's journey
$journey = UserAccessDetail::forUser($userUuid)
    ->forDate('2025-01-15')
    ->get();

// Most visited modules this month
$modules = UserAccessDetail::forUser($userUuid)
    ->thisMonth()
    ->select('module', DB::raw('SUM(visit_count) as total'))
    ->groupBy('module')
    ->orderByDesc('total')
    ->get();

// Find who accessed a module
$users = UserAccessDetail::whoAccessedModule('orders', '2025-01-01', '2025-01-31')
    ->get();
```

### 3. Use Artisan Commands

[](#3-use-artisan-commands)

```
# User stats (by national_id)
php artisan tracker:user-stats 1234567890
php artisan tracker:user-stats 1234567890 --from=2025-01-01 --to=2025-01-31
php artisan tracker:user-stats 1234567890 --role={role-uuid}

# User journey
php artisan tracker:user-journey 1234567890 --date=2025-01-15
php artisan tracker:user-journey 1234567890 --module=users

# Module access report
php artisan tracker:module-access orders --from=2025-01-01 --to=2025-01-31
php artisan tracker:module-access users --submodule=profile --role={role-uuid}

# Cleanup old records
php artisan tracker:cleanup --days=30 --dry-run
```

---

Database Schema
---------------

[](#database-schema)

### `request_trackers` - Daily Summary

[](#request_trackers---daily-summary)

**One record per** `user_uuid` + `role_uuid` + `date`

ColumnTypeDescription`uuid`UUIDPrimary key`user_uuid`UUIDUser identifier`role_uuid`UUIDRole identifier`role_name`STRINGRole name (from `roles.name`)`date`DATEActivity date`access_count`INTEGERTotal requests this day`first_access`DATETIMEFirst request timestamp`last_access`DATETIMELast request timestamp`user_session_uuid`UUIDSession identifier### `user_access_details` - Detailed Journey

[](#user_access_details---detailed-journey)

**One record per unique endpoint** per user per date (only for attributed controllers)

ColumnTypeDescription`uuid`UUIDPrimary key`tracker_uuid`UUIDFK to `request_trackers.uuid``user_uuid`UUIDUser identifier`role_uuid`UUIDRole identifier`role_name`STRINGRole name (from `roles.name`)`date`DATEVisit date`method`STRINGHTTP method (GET/POST/PUT/DELETE)`endpoint`TEXTFull path (e.g., `api/v1/users/123/profile`)`route_name`STRINGLaravel route name`controller_action`STRINGController@method`module`STRINGMain module (from `#[TrackModule]` or auto-detected)`submodule`STRINGSubmodule (from `#[TrackModule]` or auto-detected)`action`STRINGAction name (from route or method)`visit_count`INTEGERTimes visited today`first_visit`DATETIMEFirst visit timestamp`last_visit`DATETIMELast visit timestamp**Unique Constraint:** `tracker_uuid` + `endpoint` + `method`

---

Query Scopes
------------

[](#query-scopes)

### RequestTracker Scopes

[](#requesttracker-scopes)

```
->forUser($uuid)           // Filter by user
->forDate($date)           // Specific date
->forDateRange($from, $to) // Date range
->today()                  // Today
->thisWeek()               // This week
->thisMonth()              // This month
->mostActive($limit)       // Top active users
```

### UserAccessDetail Scopes

[](#useraccessdetail-scopes)

```
->forUser($uuid)
->forModule($module)
->forSubmodule($submodule)
->forDate($date)
->forDateRange($from, $to)
->today()
->thisWeek()
->thisMonth()
->mostVisited($limit)
->groupByModule()
->whoAccessedModule($module, $from, $to)
->whoAccessedSubmodule($module, $submodule, $from, $to)
```

---

Module Detection Priority
-------------------------

[](#module-detection-priority)

1. **`#[TrackModule]` Attribute** (highest priority) - Class-level attribute
2. **Custom Patterns** - Defined in `config/request-tracker.php`
3. **Route Name** - Dot notation (e.g., `users.profile.show`)
4. **URL Path** - Auto-extract from path segments
5. **Controller Name** - Extract from controller class name

---

Advanced Features
-----------------

[](#advanced-features)

### Path Exclusion

[](#path-exclusion)

```
'exclude' => [
    'health',                // Suffix match: */health
    'api/*/internal',        // Wildcard: api/v1/internal, api/v2/internal
    'regex:/^(ping|pong)/',  // Regex: starts with ping or pong
]
```

### Queue Integration

[](#queue-integration)

Package respects Laravel's `QUEUE_CONNECTION`:

- `sync` - Immediate processing (dev only)
- `redis` - Background processing (recommended)
- `database` - Database queue
- `sqs` - AWS SQS

**Important:** Run `php artisan queue:work` in production!

### Data Retention

[](#data-retention)

```
# Schedule in app/Console/Kernel.php
protected function schedule(Schedule $schedule) {
    $schedule->command('tracker:cleanup --days=90')->daily();
}
```

---

Troubleshooting
---------------

[](#troubleshooting)

**Tracking not working?**

1. Check `REQUEST_TRACKER_ENABLED=true` in `.env`
2. Run `php artisan config:cache`
3. Ensure queue worker is running: `php artisan queue:work`
4. Check logs: `tail -f storage/logs/laravel.log`

**Jobs not processing?**

1. Verify `QUEUE_CONNECTION` is correct
2. Restart worker: `php artisan queue:restart`
3. Check failed jobs: `php artisan queue:failed`

**Attribute not detected?**

1. PHP &gt;= 8.0 required (attributes)
2. Attribute must be at **class level**, not method level
3. Syntax: `#[TrackModule('module', 'submodule')]`

---

Requirements
------------

[](#requirements)

- PHP &gt;= 8.0
- Laravel 8, 9, 10, or 11
- Queue worker running (for background processing)

---

License
-------

[](#license)

MIT License

---

Support
-------

[](#support)

- **GitHub:**
- **Issues:**

---

**Made with ❤️ by [Our Education](https://github.com/our-edu)**

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance73

Regular maintenance activity

Popularity10

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 50% 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 ~1 days

Total

26

Last Release

155d ago

Major Versions

v1.0.12 → v2.0.02025-11-22

### Community

Maintainers

![](https://www.gravatar.com/avatar/bb8cec9196376674b77062736dc3226d71d0b895797d5de35bcc37b34f062b69?d=identicon)[AhmedMamdouh9950](/maintainers/AhmedMamdouh9950)

---

Top Contributors

[![AhmedMamdouh9950](https://avatars.githubusercontent.com/u/70145339?v=4)](https://github.com/AhmedMamdouh9950 "AhmedMamdouh9950 (57 commits)")[![yasminamostafa](https://avatars.githubusercontent.com/u/76902803?v=4)](https://github.com/yasminamostafa "yasminamostafa (57 commits)")

---

Tags

httprequestmiddlewarelaravelloggingtracker

### Embed Badge

![Health badge](/badges/our-education-laravel-request-tracker/health.svg)

```
[![Health](https://phpackages.com/badges/our-education-laravel-request-tracker/health.svg)](https://phpackages.com/packages/our-education-laravel-request-tracker)
```

###  Alternatives

[matthewbdaly/laravel-etag-middleware

A Laravel middleware for adding ETags to HTTP requests to improve response times

64326.0k2](/packages/matthewbdaly-laravel-etag-middleware)[tomschlick/request-migrations

HTTP Request Migrations

1844.5k](/packages/tomschlick-request-migrations)[dragon-code/laravel-http-logger

Logging incoming HTTP requests

319.8k3](/packages/dragon-code-laravel-http-logger)[laravel-shift/curl-converter

A command line tool to convert curl requests to Laravel HTTP requests.

935.3k](/packages/laravel-shift-curl-converter)[chelout/laravel-http-logger

A Laravel package to log HTTP requests, headers and sessions

272.0k](/packages/chelout-laravel-http-logger)[northwoods/router

Fast router for PSR-15 request handlers

161.4k](/packages/northwoods-router)

PHPackages © 2026

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