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.
composer require laracraft-tech/laravel-date-scopes
DateScopes trait in your Eloquent model:
use LaracraftTech\LaravelDateScopes\DateScopes;
class Transaction extends Model
{
use DateScopes;
}
// Get today's transactions
Transaction::ofToday();
// Get last week's transactions
Transaction::ofLastWeek();
created_at by default (configurable).ofLastWeek() excludes today).sum(), avg(), or where():
Transaction::ofLastWeek()->sum('amount');
Time-Based Filtering
// Dynamic time ranges
Transaction::ofLastDays($days)->get();
// Custom start date
Transaction::ofLastYear(startFrom: '2020-01-01')->get();
Custom Columns
// Use non-standard timestamp columns
Transaction::ofToday(column: 'published_at')->get();
Aggregations
// Calculate metrics
Transaction::ofLastMonth()->avg('value');
Transaction::monthToDate()->count();
Inclusive Ranges
// Override global default for specific queries
Transaction::ofLastWeek(customRange: DateRange::INCLUSIVE)->get();
public function index(Request $request)
{
$transactions = Transaction::query();
if ($request->has('days')) {
$transactions->ofLastDays($request->days);
}
return $transactions->get();
}
// Daily report job
Transaction::ofYesterday()->sum('revenue');
Transaction::ofLastHour()->each(function ($tx) {
event(new HourlyTransactionEvent($tx));
});
Inclusive vs. Exclusive:
ofLastWeek() excludes today by default. Use customRange: DateRange::INCLUSIVE to include it.Custom Columns:
CREATED_AT constant in the model if using non-standard columns:
class Transaction extends Model
{
use DateScopes;
const CREATED_AT = 'custom_column';
}
Edge Cases:
// Override in a model trait
public function scopeOfLastCentury($query)
{
return $query->whereBetween('created_at', [
now()->startOfCentury()->subYear(),
now()->endOfCentury()
]);
}
Performance:
ofLastDecade()) on large tables. Add indexes to timestamp columns.toSql():
dd(Transaction::ofLastWeek()->toSql());
created_at timestamps use the correct timezone (configure in config/app.php).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()
]);
});
Global Configuration: Publish the config to override defaults:
php artisan vendor:publish --tag="date-scopes-config"
default_range to inclusive in .env:
DATE_SCOPES_DEFAULT_RANGE=inclusive
Testing:
Mock now() for consistent tests:
use Carbon\Carbon;
Carbon::setTestNow(Carbon::parse('2023-01-01'));
// Test ofLastWeek() returns expected records
Transaction::ofLastMonth()
->where('status', 'completed')
->orderBy('amount', 'desc');
$scope = request('scope', 'week');
$query = match ($scope) {
'month' => Transaction::ofLastMonth(),
'year' => Transaction::ofLastYear(),
default => Transaction::ofLastWeek(),
};
Str::plural().
How can I help you explore Laravel packages today?