MarlonV's avatar

whereHas (events of 2023)

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?

0 likes
6 replies
m7vm7v's avatar

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();
MarlonV's avatar

@m7vm7v

Thank you for you time, but that will not give me the child-events relations of year 2023

m7vm7v's avatar

@MarlonV Apologies, misread your first message.

What about something like this -


        $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;
        });
MarlonV's avatar

@m7vm7v Almost! This gives me also a child who doesn't have events.

Thank you for your effort!

m7vm7v's avatar
m7vm7v
Best Answer
Level 51

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.

1 like
MarlonV's avatar

@m7vm7v I didn't think of simply re-filtering a result again, because that is ofcourse also possible. Thank you for your help, and insight I gained!

1 like

Please or to participate in this conversation.