I have a collection returning messages, however, I want to group them by 'subjects' and 'sender' to create 1 div for each subject, and show the latest one's created_at.
So I have:
id | senderId | receiverId | subject | message | created_at
My Controller:
$messages = Message::where('receiverId', \Auth::user()->name)
->orderBy('created_at','desc')
->paginate(10);
return view('chat')->with(compact('messages'));
So this works: dd($messages[0]->subject)
. Also, in my view, I can use @foreach
to use it as $message->created_at
. Currently it seems like this (subjects are not listed):
*yIZgT0oqH - is name
How can I group them by subject
and senderId
, and show them as 1 group(1 div) by using the latest message (created_at
)? What is the best way?
You can modify your query to do something like this, using groupBy
/ aggregation.
$messages = Message::where('receiverId', \Auth::user()->name)
->groupBy('subject')
->orderBy('created_at','desc')
->paginate(10);
Check the documentation for the same - http://laravel.com/docs/5.1/queries#ordering-grouping-limit-and-offset