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

Laravel Date Scopes Laravel Package

laracraft-tech/laravel-date-scopes

Add powerful, ready-made date query scopes to Laravel Eloquent models. Use the DateScopes trait to query records for today, last week, month-to-date, last year (with custom start dates), and more—fully chainable with builder methods and aggregations.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Pros:

    • Eloquent Integration: Seamlessly integrates with Laravel’s Eloquent ORM, leveraging existing query builder patterns. No need for custom database layers or complex migrations.
    • Granular Scoping: Provides 120+ pre-built date scopes (seconds to millenniums), reducing boilerplate for common temporal queries. Aligns well with analytics, reporting, and time-series use cases.
    • Configurability: Supports inclusive/exclusive ranges, custom column names (created_at alternatives), and per-query overrides. Flexible for domain-specific requirements (e.g., financial year vs. calendar year).
    • Chainability: Designed for method chaining (e.g., Transaction::ofLastWeek()->where(...)->sum('amount')), fitting Laravel’s fluent query style.
    • Aggregation-Friendly: Optimized for aggregations (sum, avg, count) on scoped datasets, critical for dashboards or batch processing.
  • Cons:

    • Limited to Eloquent: Not applicable to raw query builder or non-Model queries (e.g., DB::select). Requires wrapper methods if used outside Eloquent.
    • No Raw SQL Support: Scopes generate Laravel query builder syntax, which may not translate 1:1 to raw SQL for complex joins or subqueries.
    • Time Zone Assumptions: Relies on Laravel’s default timezone (config/app.php). Edge cases (e.g., multi-region apps) may need manual adjustments.

Integration Feasibility

  • Low Risk:

    • Composer Dependency: Single composer require with zero breaking changes (MIT license, no runtime hooks).
    • Zero Database Schema Changes: Works with existing created_at or custom timestamp columns. No migrations required.
    • Backward Compatibility: Supports Laravel 10+ (as of v2.5.0). Downgrade path exists for older versions.
    • Testing: Includes CI/CD workflows and unit tests. Can be validated via composer test or mock queries.
  • Potential Challenges:

    • Custom Column Names: Requires explicit configuration if models use non-standard timestamp fields (e.g., published_at).
    • Performance: Scopes generate dynamic WHERE clauses. For large tables, ensure indexes exist on scoped columns (e.g., created_at).
    • Edge Cases: Century/millennium scopes use non-intuitive ranges (e.g., "last century" = 1901–2000). Document business rules upfront.

Technical Risk

Risk Area Severity Mitigation
Inclusive/Exclusive Logic Medium Validate with stakeholders; use customRange parameter for overrides.
Time Zone Handling Low Ensure config/app.php timezone matches business requirements.
Query Performance Medium Test with EXPLAIN on large datasets; add indexes to scoped columns.
Custom Column Support Low Document per-model configurations (e.g., use DateScopes + const CREATED_AT).
Laravel Version Lock Low Pin version in composer.json (e.g., ^2.5).

Key Questions for Stakeholders

  1. Business Rules:
    • Should "last week" include today (inclusive) or exclude it (exclusive)? Default is exclusive.
    • Are there domain-specific time periods (e.g., fiscal quarters) not covered by the package?
  2. Performance:
    • Which models/tables will use these scopes? Are there queries on tables with >1M records?
    • Are there existing indexes on timestamp columns? If not, can they be added?
  3. Customization:
    • Do any models use non-standard timestamp columns (e.g., event_date instead of created_at)?
    • Are there existing date-related queries that would conflict or duplicate functionality?
  4. Testing:
    • Should inclusive/exclusive behavior be tested in UAT for critical reports?
    • Are there edge cases (e.g., leap years, DST transitions) that need validation?
  5. Maintenance:
    • Who will own updates if the package evolves (e.g., Laravel 11+ support)?
    • Should the package be forked for private modifications?

Integration Approach

Stack Fit

  • Primary Use Cases:
    • Analytics/Dashboards: Pre-built scopes for time-based aggregations (e.g., "revenue last 7 days").
    • Reporting: Generate PDF/Excel reports with filtered datasets (e.g., "orders in Q2 2023").
    • Audit Logs: Query records by time windows (e.g., "failed payments in the last hour").
    • Batch Processing: Process records in temporal chunks (e.g., "archive orders older than 1 year").
  • Anti-Patterns:
    • Avoid for real-time systems where latency is critical (scopes add query complexity).
    • Not suitable for complex joins across multiple timestamped tables (use raw queries instead).

Migration Path

  1. Assessment Phase:
    • Audit existing date-based queries (e.g., where('created_at', '>', ...)). Identify candidates for replacement.
    • Document current inclusive/exclusive expectations for each use case.
  2. Pilot Implementation:
    • Start with non-critical models (e.g., LogEntry, Notification).
    • Replace 2–3 manual queries with package scopes (e.g., LogEntry::ofLastWeek() vs. whereBetween).
    • Validate output matches expectations (e.g., row counts, aggregation sums).
  3. Full Rollout:
    • Add use DateScopes; to target models.
    • Replace manual date filters with package methods (e.g., Model::ofLastMonth()).
    • Update tests to use new scopes (replace where clauses with scope calls).
  4. Configuration:
    • Publish config (php artisan vendor:publish --tag="date-scopes-config") if default range (exclusive) doesn’t match needs.
    • Set DATE_SCOPES_DEFAULT_RANGE=inclusive in .env if required.

Compatibility

  • Laravel Versions: Tested on 10+ (v2.5.0). Use ^2.5 in composer.json for stability.
  • PHP Versions: Requires PHP 8.1+ (per Laravel 10+ compatibility).
  • Database: Works with all databases supported by Laravel (MySQL, PostgreSQL, SQLite, etc.).
  • Existing Code:
    • Breaking Changes: None. Scopes are additive.
    • Conflicts: Rare, but avoid naming collisions (e.g., custom ofLastWeek() methods in models).

Sequencing

  1. Phase 1: Replace simple where clauses (e.g., where('created_at', '>=', now()->subDays(7))ofLast7Days()).
  2. Phase 2: Migrate aggregations (e.g., where(...)->sum('amount')ofLastMonth()->sum('amount')).
  3. Phase 3: Adopt custom columns (e.g., published_at) via column parameter.
  4. Phase 4: Optimize performance (add indexes, test large datasets).

Operational Impact

Maintenance

  • Pros:
    • Minimal Overhead: No new services or cron jobs. Pure Eloquent integration.
    • Centralized Updates: Package updates handled via Composer. No manual code changes for new Laravel versions.
    • Self-Documenting: Scopes like ofLastQuarter() are more readable than raw SQL.
  • Cons:
    • Dependency Risk: If the package is abandoned, fork or replace scopes manually.
    • Configuration Drift: Global settings (e.g., default_range) may need updates if business rules change.

Support

  • Troubleshooting:
    • Common Issues:
      • Incorrect row counts due to inclusive/exclusive mismatches (validate with dd($query->toSql())).
      • Time zone offsets causing off-by-one errors (check config/app.timezone).
    • Debugging: Use ->toSql() to inspect generated queries:
      Transaction::ofLastWeek()->toSql(); // Verify WHERE clauses.
      
  • Documentation:
    • Internal Docs: Create a cheat sheet for team (e.g., "Use ofLastYear() for annual reports").
    • Edge Cases: Document non-intuitive scopes (e.g., centuries/millenniums) in a README.

Scaling

  • Performance:
    • Indexes: Ensure created_at (or custom column) is indexed. Example:
      Schema::table('transactions', function (Blueprint $table) {
          $table->index('created_at');
      });
      
    • Large Datasets: For tables >10M rows, test with EXPLAIN ANALYZE:
      DB::enableQueryLog();
      Transaction::ofLastYear
      
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport