Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Eloquent Viewable Laravel Package

cyrildewit/eloquent-viewable

Track page views on Eloquent models without external analytics. Record views (with optional cooldown), count totals or unique views, filter by period, order models by popularity, and ignore bots/crawlers. Stores each view as a DB record for flexible reporting.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Eloquent Integration: Seamlessly integrates with Laravel’s Eloquent ORM, making it ideal for applications already using Eloquent models (e.g., CMS, blogs, e-commerce). The Viewable interface and InteractsWithViews trait enforce consistency across models.
  • Analytics Scope: Lightweight alternative to third-party services (e.g., Google Analytics) for tracking model-specific views (e.g., posts, products). Avoids external dependencies and API limits.
  • Extensibility: Supports customization via traits, macros, and service provider overrides, aligning with Laravel’s modular design.

Integration Feasibility

  • Low Friction: Requires minimal setup (migration, trait implementation) and leverages Laravel’s existing infrastructure (e.g., caching, sessions).
  • Database Impact: Stores views in a dedicated table (views), which may require schema adjustments (indexes, storage) for high-traffic apps.
  • Compatibility: Supports Laravel 6.x–13.x and PHP 7.4+, with no Lumen support. Assumes standard Laravel features (e.g., sessions, cookies).

Technical Risk

  • Scalability: Individual view records can bloat the database for high-traffic models (e.g., viral posts). Mitigated by:
    • Caching: Built-in remember() method for view counts.
    • Aggregation: Suggests adding columns (e.g., unique_views_count) for faster queries.
  • Performance: Complex queries (e.g., period-based counts) may degrade without proper indexing. Requires manual optimization (e.g., adding visitor column indexes).
  • Edge Cases:
    • Crawler Detection: Defaults to blocking crawlers (e.g., Postman), which may affect testing.
    • Session Dependency: Cooldowns rely on sessions, potentially breaking in headless or stateless environments.

Key Questions

  1. Use Case Alignment:
    • Is tracking model-level views (vs. page views) a core requirement?
    • Are there existing analytics tools (e.g., Mixpanel) that could conflict?
  2. Scale Requirements:
    • What’s the expected view volume per model? (e.g., 1M+ views may need denormalization).
    • Are read-heavy queries (e.g., orderByViews) critical for performance?
  3. Customization Needs:
    • Will custom visitor data or crawler detection logic be required?
    • Are there plans to extend the View or Visitor models?
  4. Maintenance:
    • Who will manage database growth and indexing?
    • How will view data be archived or purged?

Integration Approach

Stack Fit

  • Laravel Ecosystem: Optimized for Laravel apps using Eloquent, Blade, and sessions. Avoids conflicts with Laravel’s built-in features.
  • Database: Requires a relational DB (MySQL, PostgreSQL) for the views table. No NoSQL support.
  • Caching: Leverages Laravel’s cache (Redis, Memcached) for remember() functionality. Assumes cache drivers are configured.
  • Testing: Works with Laravel’s testing tools (e.g., HTTP tests for view recording).

Migration Path

  1. Installation:
    • Composer: composer require cyrildewit/eloquent-viewable.
    • Publish migrations/config: php artisan vendor:publish --tag=migrations,config.
    • Run migrations: php artisan migrate.
  2. Model Integration:
    • Implement Viewable interface and InteractsWithViews trait in target models (e.g., Post, Product).
    • Example:
      class Post extends Model implements Viewable {
          use InteractsWithViews;
          protected $removeViewsOnDelete = true; // Optional
      }
      
  3. View Recording:
    • Trigger views($model)->record() in controllers (e.g., show() methods).
    • Example:
      public function show(Post $post) {
          views($post)->cooldown(now()->addHours(1))->record();
          return view('post.show', compact('post'));
      }
      
  4. Query Integration:
    • Replace manual view counts with fluent methods (e.g., views($post)->count()).
    • Use scopes for ordering: Post::orderByViews()->get().

Compatibility

  • Laravel Versions: Tested on 6.x–13.x. May require adjustments for newer Laravel features (e.g., model macros).
  • PHP Extensions: Relies on standard PHP extensions (e.g., session, pdo).
  • Third-Party Conflicts: No known conflicts with popular Laravel packages (e.g., Spatie’s media library), but test with eloquent-viewable first.

Sequencing

  1. Phase 1: Core Integration
    • Install package, publish migrations/config.
    • Implement Viewable trait in 1–2 pilot models (e.g., Post, Article).
    • Test view recording and basic queries (count(), unique()).
  2. Phase 2: Optimization
    • Add database indexes (e.g., visitor column) if queries are slow.
    • Implement caching for high-traffic models (e.g., remember(3600)).
  3. Phase 3: Scaling
    • Denormalize view counts (e.g., add views_count column) for read-heavy queries.
    • Schedule periodic view aggregation (e.g., Laravel command).
  4. Phase 4: Extensions
    • Customize Visitor or CrawlerDetectAdapter if needed.
    • Add macros to Views class for domain-specific logic.

Operational Impact

Maintenance

  • Database:
    • Growth Management: Monitor views table size; implement archiving/purging (e.g., soft deletes, retention policies).
    • Indexes: Regularly review and optimize indexes (e.g., composite indexes for viewable_type + viewable_id + visitor).
  • Caching:
    • Invalidate cache manually for dynamic periods (e.g., Period::subHours(1)).
    • Use cache tags or prefixes to group related view counts.
  • Dependencies:
    • Update package annually (check for Laravel version drops).
    • Monitor for breaking changes in Laravel core (e.g., Eloquent query builder).

Support

  • Troubleshooting:
    • View Not Recording: Check crawler detection (disable in testing), session configuration, or middleware blocking requests.
    • Slow Queries: Profile with Laravel Debugbar or Query Logger; add indexes or denormalize.
    • Cooldown Issues: Verify session driver and cooldown() logic in custom implementations.
  • Documentation:
    • Maintain runbooks for:
      • Resetting view counts (e.g., View::where('viewable_id', $id)->delete()).
      • Debugging crawler misclassifications.
  • Community:
    • Limited to GitHub issues (884 stars but no dependents). May need to fork for critical fixes.

Scaling

  • Horizontal Scaling:
    • Statelessness: Ensure view recording is idempotent (e.g., use ignoreMissing or transactional writes).
    • Database Replication: Read replicas for view queries; consider sharding if views table exceeds 100M rows.
  • Performance Bottlenecks:
    • Write Scaling: Batch view recordings (e.g., queue delayed jobs for bulk inserts).
    • Read Scaling:
      • Materialized views for aggregated counts (e.g., daily/monthly totals).
      • Redis for frequently accessed counts (e.g., views:post:123:count).
  • Cost:
    • Database storage costs may rise with high view volumes. Plan for archival (e.g., move old views to cold storage).

Failure Modes

Failure Scenario Impact Mitigation
Database downtime View recording/queries fail Queue view recordings; use read replicas.
Cache failure Stale view counts Fallback to DB queries; monitor cache hits.
Session store outage Cooldowns fail Use cookie-based tracking as fallback.
High cardinality in visitor Query performance degrades Add indexes; limit visitor data (e.g., hash IPs).
Migration failures Broken view tracking Backup views table; rollback strategy.
Laravel upgrade conflicts Package incompatibility Test in staging; check changelog for breaking changes.

Ramp-Up

  • Onboarding:
    • Developers:
      • Train on Viewable trait implementation and views() helper usage.
      • Document model-specific view logic (e.g., "Products ignore bots").
    • Operations:
      • Set up monitoring for views table growth and query performance.
      • Define SLAs for view count accuracy (e.g., "99% within 1 hour").
  • Testing:
    • Unit Tests: Mock Views facade to test view recording logic.
    • Integration Tests: Verify view counts in end-to
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai