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

Getting Started

Minimal Steps

  1. Installation:

    composer require laracraft-tech/laravel-date-scopes
    
  2. Usage: Add the DateScopes trait to your Eloquent model:

    use LaracraftTech\LaravelDateScopes\DateScopes;
    
    class Transaction extends Model
    {
        use DateScopes;
    }
    
  3. First Use Case: Query records from the last 7 days:

    Transaction::ofLast7Days();
    

Where to Look First

  • Scopes Documentation: Review the Scopes section in the README to understand available methods.
  • Configuration: Check the Configuration section if you need to customize default behavior (e.g., inclusive/exclusive ranges or custom created_at columns).

Implementation Patterns

Common Workflows

  1. Basic Date Filtering: Use predefined scopes for common time ranges:

    // Today's records
    Transaction::ofToday();
    
    // Last month's records
    Transaction::ofLastMonth();
    
    // Custom duration (e.g., last 48 hours)
    Transaction::ofLastHours(48);
    
  2. Chaining with Aggregations: Combine scopes with Eloquent methods for analytics:

    // Sum of amounts from last week
    Transaction::ofLastWeek()->sum('amount');
    
    // Average transaction value this month
    Transaction::monthToDate()->avg('amount');
    
  3. Custom Start Dates: Override default ranges with a startFrom parameter:

    // Records from 2020-01-01 to now
    Transaction::ofLastYear(startFrom: '2020-01-01');
    
  4. Non-Standard Columns: Use scopes on non-created_at columns (e.g., approved_at):

    Transaction::ofToday(column: 'approved_at');
    
  5. Inclusive/Exclusive Ranges: Override global defaults per query:

    // Include today in the last 7 days
    Transaction::ofLast7Days(customRange: DateRange::INCLUSIVE);
    

Integration Tips

  • Model-Level Consistency: Apply DateScopes to all relevant models (e.g., Order, Log, Event) for uniformity.
  • API Layer: Use scopes in controllers to build time-based endpoints:
    public function recentTransactions()
    {
        return Transaction::ofLast7Days()->get();
    }
    
  • Testing: Mock dates in tests to isolate scope behavior:
    $this->travelTo(now()->subDays(5));
    $records = Transaction::ofLast7Days()->get();
    

Gotchas and Tips

Pitfalls

  1. Inclusive vs. Exclusive:

    • Default is exclusive (e.g., ofLast7Days() excludes today).
    • Override globally via .env or per-query with customRange.
    • Tip: Document this behavior in your team’s style guide.
  2. Column Name Conflicts:

    • If $timestamps = false or created_at is custom-named, explicitly pass the column:
      Transaction::ofToday(column: 'custom_created_at');
      
  3. Edge Cases in Time Ranges:

    • Centuries/Millenniums: Follow astronomical definitions (e.g., ofLastCentury() spans 1901–2000).
    • Tip: Add comments or tests to clarify expectations (e.g., // Note: 2000 is included in last century).
  4. Performance:

    • Scopes add WHERE clauses. For large tables, ensure the column is indexed:
      $table->timestamp('created_at')->index();
      
  5. Time Zone Sensitivity:

    • Scopes use the system timezone. Explicitly set timezone if needed:
      Transaction::ofToday()->setTimezone('America/New_York');
      

Debugging

  • Query Inspection: Use Laravel’s query logging to verify generated SQL:

    DB::enableQueryLog();
    Transaction::ofLastWeek()->get();
    dd(DB::getQueryLog());
    
  • Custom Range Validation: If a scope behaves unexpectedly, check the customRange parameter:

    Transaction::ofLast7Days(customRange: DateRange::INCLUSIVE);
    

Extension Points

  1. Custom Scopes: Extend the trait to add domain-specific scopes:

    use LaracraftTech\LaravelDateScopes\DateScopes;
    
    class Transaction extends Model
    {
        use DateScopes;
    
        public function scopeOfLastBusinessWeek($query)
        {
            // Custom logic for business days (Mon–Fri)
        }
    }
    
  2. Dynamic Column Selection: Override the getDateColumn() method in your model:

    protected function getDateColumn()
    {
        return $this->isApproved ? 'approved_at' : 'created_at';
    }
    
  3. Configuration Overrides: Publish the config and adjust defaults:

    php artisan vendor:publish --tag="date-scopes-config"
    
    • Set default_range to inclusive in config/date-scopes.php.
  4. Localization: For multilingual apps, ensure date formats align with user locales (e.g., Carbon::setLocale()).

Pro Tips

  • Combine with Soft Deletes: Scopes work seamlessly with SoftDeletes:
    Transaction::onlyTrashed()->ofLastMonth();
    
  • Use in Relationships: Filter related models:
    $user = User::with(['transactions' => function ($query) {
        $query->ofLastYear();
    }])->find(1);
    
  • Laravel Nova: Integrate scopes into Nova toolbars for admin interfaces:
    Nova::serving(function () {
        Transaction::resolveToolbarButtonsUsing(function () {
            return [
                new ToolbarButton('LastWeek', 'last-week', function () {
                    return Transaction::ofLastWeek();
                }),
            ];
        });
    });
    
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