I have two tables related with a many-to-many relationship by a pivot table, conversations_user. I have this working fine in my controller :
Controller
public function create()
{
$loginuser = User::find(Auth::user()->id);
$user_id = $loginuser->id;
$conversations = $loginuser->conversations;
return View::make('brightcms.Conversations.Conversations',array('user_id'=>$user_id,'conversations'=>$conversations));
}
Now I want to get the conversations arranged in descending order according to a created_at
column in the conversations table + reverse() . I tried :
$conversations = $loginuser->conversations->orderBy('created_at','desc')->get()->reverse();
but it returns an error message. Thank you!
If you would like you can lazy eager load in the conversations in the order you wish
public function create()
{
$loginuser = Auth::user();
$loginuser->load(['conversations' => function($q)
{
$q->orderBy('created_at', 'desc');
}]);
View::make('....', ['user' => $loginuser]);
}
$user->conversations; // your ordered conversations collection
If you already have the collection you can sortBy
or sortByDesc
. Though as mentioned you have access to reverse
on a collection if it is in order but you just want it reversed.