You can try
Child::whereUserId(Auth::id())->whereBetween('start_date', [
Carbon::now()->startOfYear(),
Carbon::now()->endOfYear(),
]);
or
Child::whereUserId(Auth::id())->whereYear('start_date', date('Y'))->get();
Hello all,
I'm trying to retrieve event data from a child of the year 2023.
$children= Child::whereUserId(Auth::id())->whereHas('events', function ($query) {
$query->whereYear('start_date', date('Y'));
})->get();
The result is a child (so far so good) with all events recods. I need them filtered to the year 2023 only.
Anyone have an idea what I'm doing wrong here?
You could filter them further -
$children = Child::with('events')->whereUserId(Auth::id())->get()->map(function ($children) {
$children->events = $children->events->filter(function ($event) {
return $event->start_date->isCurrentYear();
});
return $children;
})->filter(function ($children) {
return $children->events->isNotEmpty();
});
That should give you a direction on how to achieve the desired results. There are definitely more optimised solutions but still, this one should give you the idea I hope.
Please or to participate in this conversation.