I'm trying to make a search query based on ages in Laravel. However, when I try to query between two dates, I get no results back. My code looks like:
$today = Carbon::today();
$age_from = $today->subYears($request->age_from)->toDateString();
$age_to = $today->subYears($request->age_to)->toDateString();
$users->whereBetween('birthday', [$age_from, $age_to]);
//Get matching users.
$users = $users->Paginate(self::paginate);
The query looks right when I review with mySql(), but for some reason, I do not get any results. Syntax error maybe? Wrong use of toDateString and comparison of MySQL's date?
EDIT: The output of $age_from is:
Carbon @959558400 {#245 ▼
date: 2000-05-29 00:00:00.0 UTC (+00:00)
}
The output of $age_to is:
Carbon @-302745600 {#245 ▼
date: 1960-05-29 00:00:00.0 UTC (+00:00)
}
The reason is that you are mutating the $today
object twice. If you check, $age_from
has the same value as $age_to
after line 3.
You should instead write:
$today = Carbon::today();
$age_from = $today->copy()->subYears($request->age_from);
$age_to = $today->copy()->subYears($request->age_to);
or simply
$age_from = Carbon::today()->subYears($request->age_from);
$age_to = Carbon::today()->subYears($request->age_to);
Credit to all, but especially both @skovmand and @Jonas Staudenmeir for helping me out; I solved the issue by facilitating @skovmand's code, and more importantly (and stupidity from my side), the dates should be swapped, so instead of [$age_from, $age_to], it is [$age_to, $age_from], as $age_to obvious is the start date. But thanks, guys! ^_^