Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Group by and get latest record of group

I am trying to group my Swipes by user_id, then I only need the latest (by created_at) Swipe per user_id. So at the end I would like to have only latest Swipes (Collection) by user_id with no duplicates.

How is this possible?

Tried something like:
Swipe::all()->sortBy('user_id')->unique('user_id')

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But latest record inside the group is not correct

>Solution :

You can try using the groupBy and max methods to achieve your desired result:

$latestSwipes = Swipe::all()->groupBy('user_id')->map(function($swipes) {
return $swipes->max('created_at');
});

This will group all the swipes by user_id and then return only the swipe with the latest created_at timestamp for each group. This will return a collection of the latest swipes by user_id with no duplicates.

Alternatively, you can use the sortByDesc and unique methods to achieve a similar result:

$latestSwipes = Swipe::all()->sortByDesc('created_at')->unique('user_id');

This will first sort the swipes in descending order by created_at timestamp and then remove any duplicate user_id values, leaving only the latest swipe per user_id in the collection.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading