Home > OS >  Get employees birthdays within next 3 days including today in Laravel
Get employees birthdays within next 3 days including today in Laravel

Time:11-09

I'm truing to get the employees that have birthday within next 3 days. I tried to do that by using the following query.

public function upcomingBirthdays()
{
    $from = now()->format('m-d');
    $to = now()->addDays(3)->format('m-d');

    $employees = Employees::whereRaw("DATE_FORMAT(dob, '%m-%d') BETWEEN '{$from}' AND '{$to}'")
                          ->where('team_id', 13)
                          ->where('status', 1)
                          ->orderBy('dob', 'DESC')
                          ->get();

    return view('frontend.employee.birthdays', compact('employees'));
}
// End Method

But this is not returning expected data.

Today is 2022-11-09

This is returning employees with birthdays between 2022-11-08 and 2022-11-10. But not returning employees that have birthdays on 11-11 and 11-12.

CodePudding user response:

The problem is probably related with the date formatting. Using DD instead of d you get a leading zero for single digit day of the month. Same for month: use MM instead of m.

Note: This will still fail for birthdays falling on January 1, 2 and 3.

CodePudding user response:

You probably need a Carbon package from nesbot to handling date. I haven't tested querying within date with built-in PHP but my code works with Carbon package.

So, on your case, try this:

$employees = Employee::whereBetween('dob', [Carbon::now(), Carbon::now()->addDay(3)])->get();
  • Related