Last active
October 10, 2022 01:46
-
-
Save jzpeepz/4f38a27fc269807f6b1523a8fef94eef to your computer and use it in GitHub Desktop.
Get recent/upcoming birthdays in Laravel
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 | |
// Note: Adding 1 to the dates below accounts for | |
// diffences between PHP date('z') [starts at zero] | |
// and MySQL DAYOFYEAR [starts at 1] | |
// Want to use specific start and end date? | |
$start = date('z', strtotime('12/1/2021')) + 1; | |
$end = date('z', strtotime('1/30/2022')) + 1; | |
// Want to use a window around a certain date? | |
$referenceDate = date('z', strtotime('12/29/2021')) + 1; | |
$start = $referenceDate - 7; // window starts 7 days ago | |
$start = $start < 1 ? $start + 366 : $end; // adjust for start dates that push back to the previous year | |
$end = $referenceDate + 7; // window ends 7 days from now | |
$end = $end > 366 ? $end - 366 : $end; // adjust for end dates that push to a new year | |
$query = \App\User::whereRaw("DAYOFYEAR(birthday) BETWEEN ? AND ?", [$start, $end]); | |
if ($end < $start) { | |
$query = $query->orWhereRaw("DAYOFYEAR(birthday) BETWEEN ? AND ?", [$start, 366]) | |
->orWhereRaw("DAYOFYEAR(birthday) BETWEEN ? AND ?", [0, $end]); | |
} | |
$users = $query->get(); |
@dwiliandy I have updated this to account for start dates that end up in the negative. Thanks for pointing out this issue!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
what happen if $start = $referenceDate - 7; is equal than -1 or -2 ?