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 Setup

  1. Installation: Add the package via Composer:
    composer require laracraft-tech/laravel-date-scopes
    
  2. Usage: Use the DateScopes trait in your Eloquent model:
    use LaracraftTech\LaravelDateScopes\DateScopes;
    
    class Transaction extends Model
    {
        use DateScopes;
    }
    
  3. First Query: Immediately start querying with built-in scopes:
    // Get today's transactions
    Transaction::ofToday();
    
    // Get last week's transactions
    Transaction::ofLastWeek();
    

Key Starting Points

  • Default Column: Uses created_at by default (configurable).
  • Inclusive/Exclusive: Defaults to exclusive ranges (e.g., ofLastWeek() excludes today).
  • Chaining: Combine with Eloquent methods like sum(), avg(), or where():
    Transaction::ofLastWeek()->sum('amount');
    

Implementation Patterns

Common Workflows

  1. Time-Based Filtering

    // Dynamic time ranges
    Transaction::ofLastDays($days)->get();
    
    // Custom start date
    Transaction::ofLastYear(startFrom: '2020-01-01')->get();
    
  2. Custom Columns

    // Use non-standard timestamp columns
    Transaction::ofToday(column: 'published_at')->get();
    
  3. Aggregations

    // Calculate metrics
    Transaction::ofLastMonth()->avg('value');
    Transaction::monthToDate()->count();
    
  4. Inclusive Ranges

    // Override global default for specific queries
    Transaction::ofLastWeek(customRange: DateRange::INCLUSIVE)->get();
    

Integration Tips

  • API Controllers: Use scopes to filter resources:
    public function index(Request $request)
    {
        $transactions = Transaction::query();
        if ($request->has('days')) {
            $transactions->ofLastDays($request->days);
        }
        return $transactions->get();
    }
    
  • Jobs/Commands: Schedule reports with time-based scopes:
    // Daily report job
    Transaction::ofYesterday()->sum('revenue');
    
  • Model Observers: Log time-based events:
    Transaction::ofLastHour()->each(function ($tx) {
        event(new HourlyTransactionEvent($tx));
    });
    

Gotchas and Tips

Pitfalls

  1. Inclusive vs. Exclusive:

    • ofLastWeek() excludes today by default. Use customRange: DateRange::INCLUSIVE to include it.
    • Tip: Clarify requirements with stakeholders—business logic may vary (e.g., "last week" in analytics vs. UI).
  2. Custom Columns:

    • Forgetting to define CREATED_AT constant in the model if using non-standard columns:
      class Transaction extends Model
      {
          use DateScopes;
          const CREATED_AT = 'custom_column';
      }
      
  3. Edge Cases:

    • Centuries/Millenniums: Follow Wikipedia’s definition (e.g., "last century" = 1901–2000). Adjust logic if needed:
      // Override in a model trait
      public function scopeOfLastCentury($query)
      {
          return $query->whereBetween('created_at', [
              now()->startOfCentury()->subYear(),
              now()->endOfCentury()
          ]);
      }
      
  4. Performance:

    • Avoid overly broad scopes (e.g., ofLastDecade()) on large tables. Add indexes to timestamp columns.

Debugging

  • Query Inspection: Use Laravel’s query logging or toSql():
    dd(Transaction::ofLastWeek()->toSql());
    
  • Timezone Issues: Ensure created_at timestamps use the correct timezone (configure in config/app.php).

Extension Points

  1. Custom Scopes: Add new scopes by extending the trait or creating a model macro:

    // In a service provider
    Transaction::macro('ofBusinessWeek', function () {
        return $this->whereBetween('created_at', [
            now()->startOfWeek()->addDay(), // Skip weekends
            now()
        ]);
    });
    
  2. Global Configuration: Publish the config to override defaults:

    php artisan vendor:publish --tag="date-scopes-config"
    
    • Set default_range to inclusive in .env:
      DATE_SCOPES_DEFAULT_RANGE=inclusive
      
  3. Testing: Mock now() for consistent tests:

    use Carbon\Carbon;
    Carbon::setTestNow(Carbon::parse('2023-01-01'));
    
    // Test ofLastWeek() returns expected records
    

Pro Tips

  • Chaining: Combine scopes with other query builders:
    Transaction::ofLastMonth()
                ->where('status', 'completed')
                ->orderBy('amount', 'desc');
    
  • Dynamic Ranges: Use request input for flexible filtering:
    $scope = request('scope', 'week');
    $query = match ($scope) {
        'month' => Transaction::ofLastMonth(),
        'year' => Transaction::ofLastYear(),
        default => Transaction::ofLastWeek(),
    };
    
  • Localization: Handle pluralization for UI (e.g., "1 day" vs. "2 days") using Laravel’s Str::plural().
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.
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
anil/file-picker
broqit/fields-ai