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 a DateScopes trait to Eloquent models to query records by common date ranges: today, last week, month-to-date, last year (with custom start), and more. Chain scopes with aggregates like sum/avg for fast stats-friendly queries.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Eloquent Integration: The package leverages Laravel’s Eloquent ORM, making it a natural fit for applications already using Laravel’s query builder. It extends Eloquent models with time-based scopes, reducing boilerplate for common date-range queries.
  • Trait-Based Design: The DateScopes trait is lightweight and non-intrusive, allowing selective adoption per model (e.g., Transaction, Order, LogEntry).
  • Query Builder Compatibility: Scopes integrate seamlessly with Laravel’s query builder, enabling chaining (e.g., Transaction::ofLastWeek()->where('status', 'completed')) and aggregations (e.g., Transaction::ofToday()->sum('amount')).
  • Customizability: Supports column overrides (e.g., approved_at instead of created_at) and custom start dates, aligning with domain-specific needs.

Integration Feasibility

  • Low Friction: Installation via Composer and a single use DateScopes statement per model. No database migrations or schema changes required.
  • Backward Compatibility: Works with Laravel 10+ (as of v2.5.0) and supports custom timestamps (e.g., custom_created_at).
  • Configuration Flexibility: Global defaults (e.g., inclusive/exclusive ranges) can be overridden per-scope or per-model, reducing rigidness.
  • Testing: Includes CI/CD workflows and unit tests, indicating reliability for production use.

Technical Risk

  • Performance Impact:
    • Scopes generate dynamic SQL queries (e.g., WHERE created_at BETWEEN ...). For large datasets, ensure indexes exist on timestamp columns (e.g., created_at).
    • Risk Mitigation: Benchmark queries in staging; consider query caching for frequent, static ranges (e.g., ofLastWeek).
  • Edge Cases:
    • Timezone Handling: Laravel’s Carbon uses the app’s timezone by default. Ensure consistency across environments (e.g., config/app.php).
    • Leap Years/Century Definitions: Scopes like ofLastCentury use Wikipedia’s convention (e.g., 20th century = 1901–2000). Validate alignment with business requirements.
  • Dependency Stability:
    • Relies on Laravel’s core (Eloquent, Carbon). Low risk unless Laravel introduces breaking changes to date handling.
    • MIT License: No legal barriers to adoption.

Key Questions

  1. Business Logic Alignment:
    • Does the exclusive/inclusive default match stakeholder expectations (e.g., "last 7 days" = 6 days ago to yesterday vs. today)?
    • Are there domain-specific date ranges (e.g., fiscal quarters) not covered by the package?
  2. Performance:
    • Will queries like ofLastYear() scale for tables with millions of records? Test with EXPLAIN ANALYZE.
    • Are there hot paths (e.g., dashboard metrics) where pre-computed aggregates (e.g., Materialized Views) could replace dynamic scopes?
  3. Customization Needs:
    • Will teams need to extend the package (e.g., add ofLastBusinessWeek)? If so, evaluate maintainability of forks vs. contributing upstream.
    • Are there non-standard timestamp columns (e.g., updated_at for "last modified") requiring custom scopes?
  4. Monitoring:
    • How will slow queries be detected and alerted? Consider integrating with Laravel Debugbar or Query Profiler.
  5. Upgrade Path:
    • What’s the deprecation policy for Laravel versions? Monitor the UPGRADING.md for breaking changes.

Integration Approach

Stack Fit

  • Laravel Ecosystem: Optimized for Laravel applications using Eloquent. No conflicts with other query-building tools (e.g., Query Builder, Scout).
  • PHP Version: Compatible with PHP 8.1+ (Laravel 10+). Verify compatibility with your stack’s minimum version.
  • Database Agnostic: Works with MySQL, PostgreSQL, SQLite, SQL Server (via Eloquent’s DBAL layer). No vendor-specific SQL.
  • Testing Tools: Integrates with Laravel’s testing helpers (e.g., refreshDatabase() for time-sensitive tests).

Migration Path

  1. Assessment Phase:
    • Audit existing date-based queries (e.g., raw SQL, custom traits) to identify replacement candidates.
    • Example: Replace Model::where('created_at', '>=', now()->subDays(7)) with Model::ofLast7Days().
  2. Pilot Phase:
    • Start with non-critical models (e.g., LogEntry, AuditTrail) to validate performance and behavior.
    • Use feature flags to toggle scope usage in queries.
  3. Rollout Phase:
    • Model-by-model adoption: Add use DateScopes; to models and refactor queries.
    • Deprecate legacy queries: Use PHPStan or Pest to flag unused raw SQL.
  4. Configuration:
    • Publish the config (php artisan vendor:publish --tag="date-scopes-config") to set global defaults (e.g., inclusive/exclusive ranges).
    • Document per-model overrides (e.g., custom columns) in a README or ADR.

Compatibility

  • Laravel Versions: Tested on 10+; verify with your version (e.g., 11.x may require adjustments).
  • Carbon Extensions: No conflicts with other Carbon-based packages (e.g., spatie/laravel-activitylog).
  • Legacy Code: Scopes do not break existing queries; they’re additive. Use IDE refactoring (e.g., PHPStorm’s "Replace with Live Template") to migrate incrementally.
  • Third-Party Packages: Check for scope naming collisions (e.g., another package’s ofLastWeek()). Prefix if needed (e.g., DateScopes::ofLastWeek()).

Sequencing

  1. Infrastructure:
    • Ensure timestamp columns (e.g., created_at) are indexed for performance.
    • Configure timezone consistency in config/app.php (e.g., timezone = 'UTC').
  2. Development:
    • Add the package to composer.json and run composer install.
    • Publish config and set global defaults (e.g., DATE_SCOPES_DEFAULT_RANGE=inclusive).
  3. Testing:
    • Write integration tests for critical scopes (e.g., ofLastMonth()) using Laravel’s TestCase.
    • Test edge cases (e.g., queries spanning DST transitions, leap seconds).
  4. Deployment:
    • Deploy to staging first; monitor query performance with Laravel Telescope.
    • Gradually roll out to production, model by model.

Operational Impact

Maintenance

  • Package Updates:
    • Monitor Packagist for new releases (e.g., Laravel 11 support).
    • Low maintenance burden: MIT license and active development (last release: 2026-04-01).
  • Custom Scopes:
    • If extending the package (e.g., adding ofLastBusinessWeek), document custom logic in a CUSTOM_SCOPES.md.
    • Consider composer scripts to auto-generate scope tests (e.g., php artisan test:scopes).
  • Deprecation:
    • Laravel’s Eloquent API changes (e.g., new query builder methods) may require package updates. Subscribe to the repo’s release notes.

Support

  • Troubleshooting:
    • Common Issues:
      • Timezone mismatches (e.g., queries return unexpected dates). Fix by setting config(['app.timezone', 'UTC']).
      • Performance bottlenecks. Optimize with indexes or pre-aggregated data.
    • Debugging Tools:
      • Use Laravel Debugbar to inspect generated SQL.
      • Enable query logging (config(['debugbar.enabled', true])).
  • Documentation:
    • Internal Runbook: Document:
      • How to add new scopes (e.g., ofLastQuarter).
      • How to override defaults (e.g., customRange: DateRange::INCLUSIVE).
      • Performance tuning (e.g., "Avoid ofLastYear() on tables >1M rows").
    • Stakeholder Training: Host a 30-minute workshop to demo scopes and best practices.

Scaling

  • Database Load:
    • High-Volume Queries: For tables with >10M records, consider:
      • Pre-aggregating data (e.g., daily summaries in a metrics table).
      • Partitioning timestamp columns (e.g., by year/month).
    • Caching: Cache frequent, static queries (e.g., ofLastWeek()) using Laravel’s cache driver:
      $
      
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