cyrildewit/eloquent-viewable
Track page views on Eloquent models without third-party analytics. Record and count total or unique views, filter by date periods, order models by views, apply cooldowns, and optionally ignore crawlers. Stores each view as a DB record for flexible querying.
Viewable interface and InteractsWithViews trait enforce consistency across models.views() helper method provides fluent syntax (e.g., views($post)->record()), reducing boilerplate and improving developer experience.viewable_id, viewable_type, optionally visitor) and caching strategies.Period::subHours(6)) complicate caching. The remember() method helps but requires manual cache invalidation for real-time updates.CrawlerDetect) may misclassify legitimate traffic (e.g., Postman). Customization is possible via CrawlerDetectAdapter.View or Visitor models (e.g., adding metadata like device type)?composer require cyrildewit/eloquent-viewable).php artisan vendor:publish).php artisan migrate).Viewable interface and InteractsWithViews trait in target models (e.g., Post, Article).class Post extends Model implements Viewable {
use InteractsWithViews;
protected $removeViewsOnDelete = true; // Optional
}
views($model)->record() in controllers or middleware (e.g., ShowPost controller).public function show(Post $post) {
views($post)->cooldown(now()->addHours(1))->record();
return view('post.show', compact('post'));
}
views($post)->period(Period::pastWeek())->count()).Post::orderByViews()->get()).remember()), queues (for batch processing), and scheduling (for periodic view aggregation).BlogPost).count(), unique()).View, Visitor, and CrawlerDetectAdapter classes for tailored behavior.viewable_id, viewable_type, and visitor (if tracking uniqueness).orderByViews) to replicas.remember() to reduce database load.| Failure Scenario | Impact | Mitigation |
|---|---|---|
| Database downtime | View recording fails | Queue views and retry on recovery. |
| Cache failure | Stale view counts | Short TTL (e.g., 5 minutes) or fallback to DB. |
| Session storage issues | Cooldowns fail | Fallback to IP/User-Agent hashing. |
| High traffic spikes | Database overload | Rate-limiting, read replicas, or aggregation. |
| Crawler misclassification | False positives/negatives | Customize CrawlerDetectAdapter. |
Viewable trait to a model.show() method.count(), period(), unique()).EXPLAIN ANALYZE) and adjust TTLs.How can I help you explore Laravel packages today?