Laravel Date Scopes

repository·main·Indexed 19 days ago

https://github.com/laracraft-tech/laravel-date-scopes

A suite of Eloquent scopes for querying records based on common time intervals such as today, last week, or month-to-date. It provides the DateScopes trait for models, supports custom timestamp columns, and allows for global or fluent configuration of inclusive and exclusive date ranges.

Tokens
2.1K
Snippets
12
Records
12
Agent score
18%

What's inside laravel-date-scopes

  1. Upgrade from v1 to v2

    main

    When upgrading from version 1 to version 2, note that a new startFrom parameter has been added to the scope methods. To avoid breaking changes caused by argument order, you should switch to using named arguments when calling scopes that pass configuration options like DateRange constants.

    // Instead of doing this (v1):
    Transaction::ofLast7Days(DateRange::INCLUSIVE);
    
    // Do this (v2) using named arguments:
    Transaction::ofLast7Days(customRange: DateRange::INCLUSIVE);
  2. Add DateScopes trait to Eloquent models

    main

    To use the date scopes, import and use the LaracraftTech\LaravelDateScopes\DateScopes trait within your Eloquent model class. Once added, you can call various date-related scopes directly on the model.

    use LaracraftTech\LaravelDateScopes\DateScopes;
    
    class Transaction extends Model
    {
        use DateScopes;
    }
    
    // Example usage:
    Transaction::ofToday();
    Transaction::ofLastWeek();
    Transaction::monthToDate();
    Transaction::ofLastYear(startFrom: '2020-01-01');
  3. Configure global date range behavior

    main

    The package allows you to define whether date ranges are inclusive (includes the current day/week/month/etc.) or exclusive (excludes the current day/week/month/etc.) globally.

    By default, the package uses an exclusive approach. To change this, publish the configuration file and update the default_range key, or use an environment variable.

    1. Publish config: php artisan vendor:publish --tag="date-scopes-config"
    2. Update .env: DATE_SCOPES_DEFAULT_RANGE=inclusive
    return [
        'default_range' => env('DATE_SCOPES_DEFAULT_RANGE', DateRange::EXCLUSIVE->value),
        'created_column' => env('DATE_SCOPES_CREATED_COLUMN', 'created_at'),
    ];
  4. Query by Days, Weeks, and Months

    main

    Use these scopes to query records based on calendar days, weeks, or months. Includes support for specific days like today and yesterday.

    // Days
    Transaction::ofToday();
    Transaction::ofYesterday();
    Transaction::ofLast7Days();
    Transaction::ofLast30Days();
    Transaction::ofLastDays(60); // Custom N days
    
    // Weeks
    Transaction::ofLastWeek();
    Transaction::ofLast2Weeks();
    Transaction::ofLastWeeks(8); // Custom N weeks
    
    // Months
    Transaction::ofLastMonth();
    Transaction::ofLast3Months();
    Transaction::ofLast12Months();
    Transaction::ofLastMonths(24); // Custom N months
  5. Query by Quarters, Years, Decades, Centuries, and Millenniums

    main

    Use these scopes for long-term historical queries.

    Note on Centuries and Millenniums: These follow standard historical definitions (e.g., the 20th century is 1901-01-01 to 2000-12-31). Ensure this aligns with your expectations for range boundaries.

    // Quarters
    Transaction::ofLastQuarter();
    Transaction::ofLast4Quarters();
    Transaction::ofLastQuarters(8);
    
    // Years
    Transaction::ofLastYear();
    Transaction::ofLastYears(2);
    
    // Decades
    Transaction::ofLastDecade();
    Transaction::ofLastDecades(2);
    
    // Centuries
    Transaction::ofLastCentury();
    Transaction::ofLastCenturies(2);
    
    // Millenniums
    Transaction::ofLastMillennium();
    Transaction::ofLastMillenniums(2);
  6. Query from start of period to current time (toNow/toDate)

    main

    These scopes query records from the beginning of the current time unit up until the present moment.

    Transaction::secondToNow();
    Transaction::minuteToNow();
    Transaction::hourToNow();
    Transaction::dayToNow();
    Transaction::weekToDate();
    Transaction::monthToDate();
    Transaction::quarterToDate();
    Transaction::yearToDate();
    Transaction::decadeToDate();
    Transaction::centuryToDate();
    Transaction::millenniumToDate();
  7. Set a custom start date for a scope

    main

    For certain scopes, you can provide a startFrom parameter to define a specific starting point for the date range instead of calculating it relative to the current time.

    // Query transactions created during the 2019-2020 period
    Transaction::ofLastYear(startFrom: '2020-01-01');
  8. Configure a custom created_at column per model

    main

    If a model uses a column name other than the default created_at for timestamps, you can define a CREATED_AT constant within your model class to tell the DateScopes trait which column to use.

    use LaracraftTech\LaravelDateScopes\DateScopes;
    
    class Transaction extends Model
    {
        use DateScopes;
        
        public $timestamps = false;
    
        const CREATED_AT = 'custom_created_at';
    }
  9. Use a custom datetime column in a scope

    main

    If you want to query a specific column that is not the model's primary timestamp column, pass the column name as the column parameter to the scope method.

    // Query based on the 'approved_at' column instead of 'created_at'
    Transaction::ofToday(column: 'approved_at');
  10. Query by Seconds, Minutes, and Hours

    main

    Use these scopes to query records based on recent time intervals. You can use predefined intervals or pass a specific number of units to the ofLast[Unit]s() method.

    // Seconds
    Transaction::ofJustNow();
    Transaction::ofLastSecond();
    Transaction::ofLast15Seconds();
    Transaction::ofLast60Seconds();
    Transaction::ofLastSeconds(120); // Custom N seconds
    
    // Minutes
    Transaction::ofLastMinute();
    Transaction::ofLast15Minutes();
    Transaction::ofLast60Minutes();
    Transaction::ofLastMinutes(120); // Custom N minutes
    
    // Hours
    Transaction::ofLastHour();
    Transaction::ofLast6Hours();
    Transaction::ofLast24Hours();
    Transaction::ofLastHours(48); // Custom N hours
  11. Specify inclusive or exclusive ranges fluently

    main

    You can override the global default range for specific queries by passing the customRange parameter to the scope. This works for most "ofLast" scopes (e.g., ofLast7Days), but is not applicable to singular scopes like ofLastHour.

    Use DateRange::INCLUSIVE or DateRange::EXCLUSIVE to specify the desired behavior.

    // Performs an inclusive query (today + previous 6 days)
    Transaction::ofLast7Days(customRange: DateRange::INCLUSIVE);