0

how I can get fetch my 10 last comments with just 1 comment per user in laravel

I saw this but I want do it with eloquent in clean way

Mahdi Majidzadeh
  • 798
  • 1
  • 14
  • 27

3 Answers3

1

Did you try

Comment::groupBy('user_id')->limit(10)->get();

If you want to get latest comments, create a class called UserComment and store latest comment_id for each user and update it for each new comment created, then You can fetch latest 10 comments by

UserComment::orderBy('updated_at')->limit(10)->get();
Anil M
  • 100
  • 8
0

This is the logic:

Comment::groupBy('user_id')->orderBy('id', 'desc')->first();

Eazy Sam
  • 288
  • 1
  • 2
  • 9
0

If you can find the latest comments by the highest ids:

$ids = Comment::selectRaw('MAX(id) id')->groupBy('user_id')->take(10)->pluck('id');
$comments = Comment::whereIn('id', $ids)->orderByDesc('id')->get();
Jonas Staudenmeir
  • 24,815
  • 6
  • 63
  • 109