The Laravel Date Scopes package provides some helpful query scopes for your Laravel Eloquent models. It was inspired by this Tweet by Livewire creator Caleb Porzio:
Would be rad if Eloquent had these, yeah? pic.twitter.com/qjOD5vv68y
— Caleb Porzio (@calebporzio) April 7, 2023
That tweet inspired the article Laravel Eloquent Models: How to Filter by Dates like a Pro with Traits by Moumen Alisawe. Which then inspired the Date Scopes package.
As found in the readme, given the following model, add the DateScopes
trait as follows:
use LaracraftTech\LaravelDateScopes\DateScopes;
class Transaction extends Model
{
use DateScopes;
}
Which gives you tons of time-based scopes. The following examples are for various hour scopes, and there are similar methods for seconds, minutes, days, weeks, months, years, decades, and so on:
// query transactions created during the last hour
Transaction::ofLastHour();
// query transactions created during the last 6 hours
Transaction::ofLast6Hours();
// query transactions created during the last 12 hours
Transaction::ofLast12Hours();
// query transactions created during the last 18 hours
Transaction::ofLast18Hours();
// query transactions created during the last 24 hours
Transaction::ofLast24Hours();
// query transactions created during the last N hours
Transaction::ofLastHours(48);
Here's an example of how to get all transactions in the last year using the lastYear()
date scope:
$transactions = Transaction::lastYear()->get();
I love how this idea was built upon through contributions of multiple people in the Laravel community. From inspiration, to example, to a package that you can easily install in your Laravel application! 👏
To get started, you can learn more about this package, get full installation instructions, and view the source code on GitHub.