Stephan-v Stephan-v - 1 year ago 89
PHP Question

How to sort this eloquent collection?

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);

I now have a collection of the logged in user and their friends and ultimately want to display some sort of timeline with their checkins. My main issue is that whenever I want to use something like this:

@foreach($users as $user)
@foreach($user->checkins as $checkin)
// my code

I get all users checkins but I am getting the output chunked/grouped per user. Preferably I would just like to sort them on age and not per user so I can create an actual timeline. Now I am getting a block of all of user 1's checkins followed by a block of user 2's checkins, etc.

How can I prevent this behaviour and simply show the latest checkin down to the oldest one?

Answer Source

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

You might need to adapt the code to match your column/relation names, but it should give you an idea how to solve it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download