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 hourTransaction::ofLastHour(); // query transactions created during the last 6 hoursTransaction::ofLast6Hours(); // query transactions created during the last 12 hoursTransaction::ofLast12Hours(); // query transactions created during the last 18 hoursTransaction::ofLast18Hours(); // query transactions created during the last 24 hoursTransaction::ofLast24Hours(); // query transactions created during the last N hoursTransaction::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.
Filed in:
Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.