Skip to content

Instantly share code, notes, and snippets.

@papalardo
Last active December 22, 2022 17:56
Show Gist options
  • Save papalardo/7e85b60b1c3bab4ee42069f63be3c10d to your computer and use it in GitHub Desktop.
Save papalardo/7e85b60b1c3bab4ee42069f63be3c10d to your computer and use it in GitHub Desktop.
Get birthdays users laravel
<?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