Last active
April 10, 2023 20:25
-
-
Save radermacher/1555704a3e123de024581899ce9aaf84 to your computer and use it in GitHub Desktop.
# Laravel Eloquent Models: How to Filter by Dates. Source: https://medium.com/@moumenalisawe/laravel-eloquent-models-how-to-filter-by-dates-like-a-pro-with-traits-834c77e6b45a
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Traits; | |
use Carbon\Carbon; | |
trait FilterableByDates | |
{ | |
public function scopeToday($query, $column = 'created_at') | |
{ | |
return $query->whereDate($column, Carbon::today()); | |
} | |
public function scopeYesterday($query, $column = 'created_at') | |
{ | |
return $query->whereDate($column, Carbon::yesterday()); | |
} | |
public function scopeMonthToDate($query, $column = 'created_at') | |
{ | |
return $query->whereBetween($column, [Carbon::now()->startOfMonth(), Carbon::now()]); | |
} | |
public function scopeQuarterToDate($query, $column = 'created_at') | |
{ | |
$now = Carbon::now(); | |
return $query->whereBetween($column, [$now->startOfQuarter(), $now]); | |
} | |
public function scopeYearToDate($query, $column = 'created_at') | |
{ | |
return $query->whereBetween($column, [Carbon::now()->startOfYear(), Carbon::now()]); | |
} | |
public function scopeLast7Days($query, $column = 'created_at') | |
{ | |
return $query->whereBetween($column, [Carbon::today()->subDays(6), Carbon::now()]); | |
} | |
public function scopeLast30Days($query, $column = 'created_at') | |
{ | |
return $query->whereBetween($column, [Carbon::today()->subDays(29), Carbon::now()]); | |
} | |
public function scopeLastQuarter($query, $column = 'created_at') | |
{ | |
$now = Carbon::now(); | |
return $query->whereBetween($column, [$now->startOfQuarter()->subMonths(3), $now->startOfQuarter()]); | |
} | |
public function scopeLastYear($query, $column = 'created_at') | |
{ | |
return $query->whereBetween($column, [Carbon::now()->subYear(), Carbon::now()]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment