stalwart1014
stalwart1014

Reputation: 471

Get latest data of a specific column using eloquent

How do i get the last/latest data of each specific user_id.

Submission table

id user_id status created_at updated_at
1 3 redo somedatetime somedatetime => dont want this
2 3 redo somedatetime somedatetime
3 4 redo somedatetime somedatetime
4 5 redo somedatetime somedatetime

ID 2 is not a redundancy. I'm keeping track of the records. I need to grab id 2,3,4. I've tried using

Submission::where('status','redo')->distinct('user_id')->get();

but it returns all the value

UPDATE

For reference purpose here is the real structure of the table

Submission table

as you can see user_id 78 has 2 redos which is 89 and 90. Im trying to get the latest/last one which is 90.

Upvotes: 0

Views: 345

Answers (2)

lagbox
lagbox

Reputation: 50491

You can try this with a sub query:

Submission::from(Submission::orderBy('id', 'desc'), 't')
    ->groupBy('user_id')
    ->get();

Probably will have to make adjustments, not tested, but the idea is a sub query would get the ordering then the main query would do the grouping.

Upvotes: 2

OMR
OMR

Reputation: 12188

you can get the last ids then get the complete records:

 $max_ids = Submission::query()
       ->where('status','redo')

        ->select('user_id', DB::raw('max(id) max_ids'))
        ->groupBy('user_id')->pluck('max_ids');

    $lasts = Submission::whereIn('id', $max_ids)->get();

Upvotes: 2

Related Questions