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 seamless fit for applications already using Laravel’s query builder. It extends Eloquent models with fluent date-based scopes, aligning with Laravel’s convention-over-configuration philosophy.
  • Trait-Based Design: The use of a trait (DateScopes) ensures minimal boilerplate and avoids polluting the global namespace. This is ideal for modular Laravel applications where traits are preferred over base classes for inheritance.
  • Customizability: Supports custom date columns (e.g., approved_at), inclusive/exclusive ranges, and fluent configuration, which aligns with Laravel’s flexibility for domain-specific adaptations.

Integration Feasibility

  • Low Coupling: The package is self-contained and doesn’t impose global constraints (e.g., no forced created_at column). It can be adopted incrementally, model-by-model.
  • Backward Compatibility: Supports Laravel 10+ (as of v2.5.0), with clear upgrade paths documented. Existing queries using raw where clauses remain unaffected.
  • Database Agnostic: Works with any database supported by Laravel (MySQL, PostgreSQL, SQLite, etc.), as it relies on Eloquent’s query builder.

Technical Risk

  • Inclusive/Exclusive Logic: The default exclusive range for scopes like ofLastWeek() may misalign with business expectations (e.g., "last 7 days" might be interpreted as inclusive in analytics). Requires stakeholder validation.
  • Performance: Scopes generate dynamic where clauses, which could impact query performance on large datasets if not indexed. Requires proper database indexing (e.g., created_at).
  • Edge Cases: Timezone handling isn’t explicitly documented. Assumes now() uses the app’s timezone (configurable in Laravel). May need validation for multi-timezone apps.
  • Custom Column Support: While flexible, using non-standard columns (e.g., approved_at) requires explicit configuration per model, adding maintenance overhead.

Key Questions

  1. Business Requirements:
    • Should date ranges default to inclusive or exclusive? (Configurable but requires alignment with stakeholders.)
    • Are there specific timezones or daylight saving edge cases to handle?
  2. Performance:
    • Are created_at columns indexed? If not, will this package introduce performance bottlenecks?
    • Will queries be chained with aggregations (e.g., ofLastWeek()->sum('amount')), requiring optimized database stats?
  3. Adoption Strategy:
    • Should this be applied globally (via a base model) or selectively (per model)?
    • How will custom columns (e.g., published_at) be managed across the codebase?
  4. Testing:
    • Are there existing unit/integration tests for date-based queries? How will this package’s scopes be validated?
  5. Future-Proofing:
    • Does the app use Laravel’s query caching or database views that could conflict with dynamic scopes?
    • Are there plans to support Laravel 11+ features (e.g., new query builder methods)?

Integration Approach

Stack Fit

  • Laravel Ecosystem: Perfectly aligned with Laravel’s Eloquent and query builder. No external dependencies beyond Laravel itself.
  • PHP Version: Compatible with PHP 8.1+ (Laravel 10+), ensuring modern PHP features (e.g., named arguments, attributes) are leveraged.
  • Tooling: Works with Laravel’s artisan commands, migrations, and testing tools (e.g., Pest/PHPUnit).

Migration Path

  1. Assessment Phase:
    • Audit existing date-based queries (e.g., where('created_at', '>=', ...)) to identify candidates for replacement.
    • Validate business logic for inclusive/exclusive ranges (e.g., "last week" in reports vs. APIs).
  2. Incremental Adoption:
    • Start with a single model (e.g., Transaction) to test the trait and scopes.
    • Gradually apply to other models, prioritizing high-impact queries (e.g., dashboards, analytics).
  3. Configuration:
    • Publish the config file (php artisan vendor:publish --tag="date-scopes-config") to set global defaults (e.g., default_range).
    • Override defaults per model if needed (e.g., Transaction::ofLastWeek(customRange: DateRange::INCLUSIVE)).
  4. Deprecation:
    • Replace raw where clauses with scopes in new code.
    • Use Laravel’s deprecate() helper to warn about legacy queries in CI/CD.

Compatibility

  • Laravel Versions: Officially supports Laravel 10+ (as of v2.5.0). Test compatibility with Laravel 11+ if adopting early.
  • Database Drivers: No driver-specific code; works with all Laravel-supported databases.
  • Legacy Code: Can coexist with existing queries but may require refactoring for consistency.

Sequencing

  1. Pre-requisites:
    • Ensure Laravel 10+ and PHP 8.1+ are used.
    • Verify database indexes exist on date columns (e.g., created_at).
  2. Core Integration:
    • Install via Composer: composer require laracraft-tech/laravel-date-scopes.
    • Add the trait to target models: use LaracraftTech\LaravelDateScopes\DateScopes.
  3. Configuration:
    • Publish and configure the package (e.g., set default_range in .env).
    • Test edge cases (e.g., custom columns, timezones).
  4. Validation:
    • Run existing tests to ensure no regressions.
    • Add integration tests for new scopes (e.g., Transaction::ofLastWeek()).
  5. Rollout:
    • Deploy to staging, monitor query performance.
    • Gradually replace legacy queries in production.

Operational Impact

Maintenance

  • Package Updates: Monitor for Laravel version compatibility (e.g., v2.5.0 adds Laravel 13 support). Use composer update cautiously.
  • Customizations: Overrides (e.g., custom columns, ranges) may require updates if the package evolves. Document these in a README or wiki.
  • Deprecations: Watch for breaking changes in the UPGRADING.md file.

Support

  • Troubleshooting:
    • Common issues: Timezone mismatches, missing indexes, or inclusive/exclusive logic errors.
    • Debugging tip: Use ->toSql() on queries to verify generated SQL.
  • Documentation:
    • The package’s README is comprehensive but may lack real-world examples. Supplement with internal docs for custom use cases.
  • Community: Active GitHub repo (515 stars, recent releases) but limited dependents (0). May require internal support for niche issues.

Scaling

  • Performance:
    • Indexes: Ensure created_at (or custom columns) are indexed. Add composite indexes if queries filter by multiple date ranges.
    • Caching: For read-heavy apps, cache frequent queries (e.g., Transaction::ofLastWeek()) using Laravel’s cache or Redis.
    • Database Load: Dynamic scopes may increase query complexity. Monitor slow queries with Laravel Debugbar or database profiling.
  • Horizontal Scaling: No impact on scaling Laravel apps (e.g., queues, Horizon). Scopes are resolved at query time.

Failure Modes

  • Incorrect Ranges: Business logic errors if inclusive/exclusive defaults misalign with expectations (e.g., "last week" includes/excludes today).
  • Timezone Issues: Queries may return unexpected results if the app’s timezone differs from the database’s. Use config(['app.timezone' => 'UTC']) consistently.
  • Custom Column Errors: Typos in column names (e.g., approved_at vs. approvedOn) will cause silent failures. Validate in tests.
  • Database Downtime: Like all queries, scopes fail if the database is unavailable. Use Laravel’s retry mechanisms for critical queries.

Ramp-Up

  • Developer Onboarding:
    • Training: 30-minute session to demo scopes (e.g., ofLastWeek(), monthToDate()) and configuration.
    • Coding Standards: Enforce consistent use (e.g., prefer scopes over raw where clauses).
  • Testing:
    • Add test cases for new scopes in the model’s test suite. Example:
      public function test_of_last_week()
      {
          $oldTransaction = Transaction::factory()->create();
          $newTransaction = Transaction::factory()->create();
      
          $this->assertCount(1, Transaction::ofLastWeek()->get());
          // Ensure $newTransaction is excluded if using exclusive range
      }
      
  • Documentation:
    • Create a internal wiki page with:
      • List of adopted models and their scopes.
      • Examples of chained queries (e.g., ofLastMonth()->where('status', 'active')).
      • Troubleshooting tips (e.g., "If ofToday() returns no results, check your timezone.").
  • Feedback Loop:
    • Gather input from developers using the package to identify missing scopes (e.g., "quarter-to-date" for fiscal years).
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.
hamzi/corewatch
minionfactory/raw-hydrator
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