Get latest message (row) per user in Laravel

后端 未结 9 1097
逝去的感伤
逝去的感伤 2021-02-19 01:37

TL;DR: Need latest message from each sender.

In my Laravel application I have two tables:

Users:

  • id
  • name

Messages:

9条回答
  •  耶瑟儿~
    2021-02-19 01:51

    Maybe you can try this one:

            $user = \Auth::user(); 
    
            // Get the latest date
            $last_date_created = Message::latest()->first()->created_at; // also check for possible null
    
            // Get the date only - use to specify date range in the where section in the eloquent query
            $target_date = date('Y-m-d', strtotime( $last_date_created ) );
    
            // Retrieve the messages
            $latest_posts = Message::where('recipient_id', $user->id)
                                   ->where('created_at', '>=', $target_date . ' 00:00:00')
                                   ->where('created_at', '<=',  $target_date . ' 23:59:59')
                                   ->groupBy('sender_id')
                                   ->groupBy('created_at')
                                   ->get();
    
            return $latest_posts;
    

    This may not be very efficient since it took two queries to do the job but you will gain benefits thru code readability.

    I hope it works the way it should be. I haven't tested it though but that's how I usually do this... Cheers!

提交回复
热议问题