I am currently working on a beer application with checkins. A user checkin represents a beer he/she has drank. I am now dealing with checkins of the currently logged in user and also the checkins of their friends which I have set up through a friendship table.
I am grabbing a collection of user friends and an instance of the currently logged in user and I am adding them together like so:
// merge the currently logged in user with their friends
$users = $users->add($user);
@foreach($users as $user)
@foreach($user->checkins as $checkin)
// my code
As you're iterating through users, and only then through their checkins, you're seeing checkins grouped by user. In order to be able to order checkins by age, you need to iterate through checkins directly.
The following should help:
// get IDs of users for which you want to show checkins $users = $users->add($user); $userIds = $users->modelKeys(); // load checkins for those users $checkins = Checkin::whereIn('user_id', $userIds)->orderBy('created_at', 'desc')->with('user')->get();
The $checkins variable will hold list of checkins, ordered by their creation date with latest checkins first. Each of the rows will hold the corresponding user in its user attribute.
You should be able to iterate through all checkins now with:
@foreach($checkins as $checkin) // your code here // user is available in $checkin->user @endforeach
You might need to adapt the code to match your column/relation names, but it should give you an idea how to solve it.