Reputation: 1121
I'm building a simple message box. Each message belongs to a conversation. What I'm trying to do is get the last 5 messages in the conversation and order them by ascending.
InboxController.php
public function messages($hashedId)
{
$conversation = Conversation::where('hashed_id', $hashedId)->first();
$messages = Message::where('conversation_id', $conversation->id)
->latest()
->take(5)
->get();
$messages->orderBy('created_at','asc');
return MessageResource::collection($messages);
}
Error
BadMethodCallException: Method Illuminate\Database\Eloquent\Collection::orderBy does not exist.
Upvotes: 2
Views: 461
Reputation: 1540
Use sortBy
function. Collection doesn;t have an function named orderBy.
$collection->sortBy('created_at');
Reference:- https://laravel.com/docs/5.8/collections#method-sortby
Upvotes: 1
Reputation: 4826
try this
public function messages($hashedId)
{
$conversation = Conversation::where('hashed_id', $hashedId)->first();
$messages = Message::where('conversation_id', $conversation->id)
->take(5)
->orderBy('created_at','desc')
->get();
return MessageResource::collection($messages);
}
Upvotes: 1