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.
Installation:
composer require laracraft-tech/laravel-date-scopes
Usage:
Add the DateScopes trait to your Eloquent model:
use LaracraftTech\LaravelDateScopes\DateScopes;
class Transaction extends Model
{
use DateScopes;
}
First Use Case: Query records from the last 7 days:
Transaction::ofLast7Days();
created_at columns).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);
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');
Custom Start Dates:
Override default ranges with a startFrom parameter:
// Records from 2020-01-01 to now
Transaction::ofLastYear(startFrom: '2020-01-01');
Non-Standard Columns:
Use scopes on non-created_at columns (e.g., approved_at):
Transaction::ofToday(column: 'approved_at');
Inclusive/Exclusive Ranges: Override global defaults per query:
// Include today in the last 7 days
Transaction::ofLast7Days(customRange: DateRange::INCLUSIVE);
DateScopes to all relevant models (e.g., Order, Log, Event) for uniformity.public function recentTransactions()
{
return Transaction::ofLast7Days()->get();
}
$this->travelTo(now()->subDays(5));
$records = Transaction::ofLast7Days()->get();
Inclusive vs. Exclusive:
ofLast7Days() excludes today)..env or per-query with customRange.Column Name Conflicts:
$timestamps = false or created_at is custom-named, explicitly pass the column:
Transaction::ofToday(column: 'custom_created_at');
Edge Cases in Time Ranges:
ofLastCentury() spans 1901–2000).// Note: 2000 is included in last century).Performance:
WHERE clauses. For large tables, ensure the column is indexed:
$table->timestamp('created_at')->index();
Time Zone Sensitivity:
Transaction::ofToday()->setTimezone('America/New_York');
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);
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)
}
}
Dynamic Column Selection:
Override the getDateColumn() method in your model:
protected function getDateColumn()
{
return $this->isApproved ? 'approved_at' : 'created_at';
}
Configuration Overrides: Publish the config and adjust defaults:
php artisan vendor:publish --tag="date-scopes-config"
default_range to inclusive in config/date-scopes.php.Localization:
For multilingual apps, ensure date formats align with user locales (e.g., Carbon::setLocale()).
SoftDeletes:
Transaction::onlyTrashed()->ofLastMonth();
$user = User::with(['transactions' => function ($query) {
$query->ofLastYear();
}])->find(1);
Nova::serving(function () {
Transaction::resolveToolbarButtonsUsing(function () {
return [
new ToolbarButton('LastWeek', 'last-week', function () {
return Transaction::ofLastWeek();
}),
];
});
});
How can I help you explore Laravel packages today?