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 and query page views on Eloquent models without external analytics. Record views with optional cooldown, count totals/unique views, filter by date periods, order models by views, and ignore crawlers. Stores each view as a DB record.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Seamless Eloquent Integration: The package leverages Laravel’s Eloquent ORM, making it a natural fit for applications already using Eloquent models. It extends functionality without requiring architectural overhauls.
  • Minimalist Design: Focuses on a single, well-defined use case (view tracking) without bloating the codebase, aligning with Laravel’s philosophy of simplicity.
  • Database-Centric: Stores views in a dedicated table, enabling granular queries (e.g., time-based, unique views) but introduces storage overhead. This is ideal for applications prioritizing analytics precision over scalability.

Integration Feasibility

  • Laravel 6+ Compatibility: Supports modern Laravel versions (6.x–13.x), ensuring compatibility with most active projects. PHP 7.4+ requirement aligns with current Laravel standards.
  • Zero Dependents: No external dependencies beyond Laravel core, reducing integration friction.
  • Migration-First Approach: Requires publishing migrations and running migrate, which is straightforward but may require downtime in production.

Technical Risk

  • Database Growth: Individual view records can bloat storage for high-traffic applications. Mitigation: Implement caching (built-in) or periodic aggregation (e.g., via Laravel queues).
  • Performance at Scale: Complex queries (e.g., Period::create() with large date ranges) may strain the database. Indexes on viewable_id and viewable_type are provided, but additional tuning (e.g., visitor column indexing) may be needed.
  • Crawler Detection: Default crawler filtering (e.g., Postman) might inadvertently block legitimate bots or testing tools. Customization is possible via CrawlerDetectAdapter.
  • Session Dependency: Cooldown functionality relies on sessions, which could fail in stateless environments (e.g., API-only apps) or with distributed caching.

Key Questions

  1. Analytics Granularity vs. Storage Cost:

    • Does the team prioritize precise, queryable view data (e.g., "views between Jan 1–Feb 1") over storage efficiency?
    • If storage is a concern, how will aggregated metrics (e.g., daily view counts) be handled?
  2. Performance Tradeoffs:

    • Are there plans to pre-aggregate view data (e.g., via Laravel queues) to offset query performance?
    • Will the visitor column be indexed for unique view queries?
  3. Environment Compatibility:

    • Is the application session-based (e.g., web) or stateless (e.g., API)? If stateless, how will cooldowns be managed?
    • Are there non-Laravel frontend frameworks (e.g., React, Vue) that need view tracking? If so, how will the package integrate (e.g., via API endpoints)?
  4. Extensibility Needs:

    • Are custom visitor attributes (e.g., user roles, devices) required? The package supports this via Visitor class extension.
    • Will multiple view collections (e.g., "public," "admin") be needed? The collection() method supports this.
  5. Testing and Crawlers:

    • How will testing (e.g., Postman, automated scripts) interact with crawler detection? Custom CrawlerDetectAdapter may be needed.
    • Are there false positives/negatives in crawler detection that need addressing?

Integration Approach

Stack Fit

  • Laravel-Centric: Optimized for Laravel’s ecosystem (Eloquent, service providers, migrations). No conflicts with Laravel’s core or popular packages (e.g., Laravel Scout, Laravel Nova).
  • PHP 7.4+: Aligns with Laravel’s current PHP requirements, ensuring compatibility with modern PHP features (e.g., typed properties, attributes).
  • Database Agnostic: Works with Laravel’s supported databases (MySQL, PostgreSQL, SQLite, SQL Server) without vendor-specific logic.

Migration Path

  1. Installation:

    • Composer: composer require cyrildewit/eloquent-viewable.
    • Publish migrations: php artisan vendor:publish --provider="CyrildeWit\EloquentViewable\EloquentViewableServiceProvider" --tag="migrations".
    • Run migrations: php artisan migrate.
    • (Optional) Publish config: php artisan vendor:publish --tag="config".
  2. Model Integration:

    • Implement Viewable interface and InteractsWithViews trait in target models (e.g., Post, Article).
    • Example:
      use CyrildeWit\EloquentViewable\Contracts\Viewable;
      use CyrildeWit\EloquentViewable\InteractsWithViews;
      
      class Post extends Model implements Viewable {
          use InteractsWithViews;
      }
      
  3. View Recording:

    • Integrate views($model)->record() in controllers or middleware (e.g., HandleViewTracking middleware).
    • Example (controller):
      public function show(Post $post) {
          views($post)->record();
          return view('post.show', compact('post'));
      }
      
  4. Query Integration:

    • Replace manual view counting with fluent methods (e.g., views($post)->count()).
    • Use scopes for ordering: Post::orderByViews()->get().

Compatibility

  • Laravel Versions: Tested on 6.x–13.x. For LTS releases (e.g., 10.x, 11.x), verify no breaking changes in the package’s composer.json.
  • Database Schema: Default migration creates views table with viewable_id, viewable_type, visitor, and timestamps. Customize via php artisan vendor:publish --tag="migrations".
  • Caching: Built-in remember() method integrates with Laravel’s cache (e.g., Redis, file, database). Configure cache driver in .env.
  • Testing: Exclude crawlers by default (Postman, bots). Override via CrawlerDetectAdapter if needed.

Sequencing

  1. Phase 1: Core Integration

    • Install package, publish migrations, and run migrations.
    • Implement Viewable trait in 1–2 pilot models (e.g., Post, Product).
    • Test view recording in controllers and basic queries (count(), period()).
  2. Phase 2: Analytics Expansion

    • Add cooldowns for high-value models (e.g., views($post)->cooldown(now()->addHours(2))->record()).
    • Implement caching for frequently accessed views (e.g., dashboard metrics).
    • Optimize database with indexes (e.g., visitor column) if unique views are critical.
  3. Phase 3: Scaling and Extensions

    • Extend Visitor class for custom attributes (e.g., user_id, device_type).
    • Implement periodic aggregation (e.g., Laravel command to update unique_views_count column).
    • Customize crawler detection if false positives/negatives are identified.
  4. Phase 4: Monitoring

    • Monitor database growth and query performance (e.g., EXPLAIN on complex Period queries).
    • Adjust caching strategies based on hit/miss ratios.

Operational Impact

Maintenance

  • Package Updates:
    • Monitor for updates via Packagist or Laravel’s composer outdated. The package is actively maintained (last release: 2026-03-28).
    • Test updates in staging for breaking changes (e.g., Laravel version drops).
  • Database Schema:
    • Schema changes (e.g., new columns) require migrations. Follow Laravel’s migration conventions.
    • Backup the views table before major updates or schema modifications.
  • Dependencies:
    • No external dependencies beyond Laravel core, reducing maintenance overhead.

Support

  • Troubleshooting:
    • Common issues: Crawler misclassification, cooldown session failures, or slow queries. Debug with:
      • dd(views($post)->toQuery()) to inspect generated SQL.
      • config('viewable') to verify configuration.
    • Log view recording failures (e.g., session issues) for stateless environments.
  • Documentation:
    • Comprehensive README with examples for installation, usage, and optimization. Extending the package (e.g., custom Visitor) is well-documented.
    • Community support via GitHub issues (885 stars, active maintenance).

Scaling

  • Database Scaling:
    • Vertical: Add indexes (e.g., visitor) and optimize queries (e.g., Period ranges).
    • Horizontal: For distributed setups, ensure session storage (e.g., Redis) is shared across instances to maintain cooldown consistency.
    • Archival: Implement a strategy for archiving old views (e.g., partition tables by year) to reduce query load.
  • Caching:
    • Aggressive caching (remember()) for dashboard metrics or frequently accessed views.
    • Cache invalidation: Use Laravel’s cache tags or event listeners (e.g., eloquent.deleted) to clear cached views when models are updated/deleted.
  • Asynchronous Processing:
    • Offload view recording to queues (e.g., Laravel Queues) for high-traffic endpoints to avoid blocking requests.
    • Example:
      views($post)->record(); // Sync
      // OR
      
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony