Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mallorca's avatar

Refactor so that activities are displayed by event date

Hi artisans!

I followed Jeffs series on activity feed. Right now, I have in my route this:

$userevent = User::with('event')->get();

Then in my view, I have something like this:

    @foreach ($userevent as $user)
        @foreach($user->activity as $event)
            @include ("activity.type.{$event->name}")
        @endforeach
    @endforeach

I have added ->latest(); in the model so that the latest activities are shown. Problem is right now it shows the latest activity for the users and it sorts the list by users. If I add ->latest() in the route, it will show the latest activity first but then it shows of that users activities, no matter how long ago they were added. I would like to sort it so that the activities are always sorted by event date, no matter who the user is.

I guess I would need to change the two foreach loops, but I'm a bit sure how to refactor so that it works in this case. Would really appreciate if someone could help me out here.

0 likes
4 replies
mallorca's avatar

@JarekTkaczyk amazing, your simple but eye-opening solution the trick! I was "thinking inside a box" of having to call the user with activity and never thought about the other way around.

Thanks a lot!

JarekTkaczyk's avatar

@Augustus the best shot is just take a break, a coffee or something, then come back with fresh mind and you can see the bigger picture much easier.

1 like

Please or to participate in this conversation.