Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent Birthdays Query to get Date Column based on Date and Month only

I have a date() column in mysql which has the Date of Birth in mysql’s YYYY-MM-DD format:

$table->date('dob')->nullable();

I am trying to query this table so it lists all users who are having birthdays from today till next 7 days. I have something like this right now:

$date = new Carbon;
$today = $date->format('Y-m-d');
$futureDays = $date->addDays(7)->format('Y-m-d');

$birthdays = SiteUsers::where('dob', '>=', $today)
                        ->where('dob', '<=', $futureDays)
                        ->orderBy('dob', 'ASC')
                        ->get();

The problem with the above query is that it only lists the users having DOB with the exact dates in this year only which is not right. What I really want is to list the users having birthdays irrespective of the year they were born by matching only the ‘date’ and ‘month’ and ignoring the ‘year’.

I don’t know how to achieve that. Can someone help me out please…

like image 518
Neel Avatar asked Oct 15 '25 03:10

Neel


1 Answers

Shortly after I posted my question, I tried a method using raw queries that uses DateOfYear() SQL Function. So this is what I have now which seems to be working by getting the users with birthdays in the next 7 days irrespective of the year:

$birthdays = SiteUsers::whereRaw('DAYOFYEAR(curdate()) <= DAYOFYEAR(dob) AND DAYOFYEAR(curdate()) + 7 >=  dayofyear(dob)')
                        ->orderByRaw('DAYOFYEAR(dob)')
                        ->get();

enjoy

like image 154
Neel Avatar answered Oct 17 '25 12:10

Neel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!