Last active
December 22, 2022 17:56
-
-
Save papalardo/7e85b60b1c3bab4ee42069f63be3c10d to your computer and use it in GitHub Desktop.
Get birthdays users laravel
This file contains 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 | |
use Carbon\CarbonPeriod; | |
// On user model | |
public function scopeBirthdayBetween($query, $dateBegin, $dateEnd) | |
{ | |
$period = CarbonPeriod::create($dateBegin, $dateEnd); | |
foreach ($period as $key => $date) { | |
$queryFn = function($query) use ($date) { | |
$query->whereMonth("birthday", '=', $date->format('m'))->whereDay("birthday", '=', $date->format('d')); | |
}; | |
if($key === 0) { | |
$queryFn($query); | |
} else { | |
$query->orWhere(function($q) use ($queryFn) { | |
$queryFn($q); | |
}); | |
} | |
} | |
return $query; | |
} | |
// Usage | |
User::birthdayBetween( | |
Carbon\Carbon::now()->toDateString(), | |
Carbon\Carbon::now()->addDays(7)->toDateString() | |
)->get(); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment