Search code examples
mysqllaravellaravel-query-builder

Get all records where age is less than from a date difference in laravel


I'm trying to get all the records of children for which age is less than 5 years.

The date to calculate age should be a future date e.g 2021-08-12

$date and $age are custom.

$date can be any future date and $age is a number (e.g 5)

I have written the following but it is not working.

$children=Child::whereRaw('DATEDIFF('.$date.', date_of_birth) < '.$age.'')
                ->get();

Here date_of_birth is a column in DB.


Solution

  • Finally after debugging i found a solution. The problem was that the $date was not passed as string due to which there were no days found and I had to convert the days into years. This may help to someone.

    $children=Child::whereRaw('(DATEDIFF("'.$date.'",date_of_birth)/365) < '.$age.'')
              ->get();