So I have two collections one has posts made by the user that's logged in the other is posts made by users that he is following. I want to merge these two collections together and then sort them as one collection. this is what I tried:
$feed = $friendPosts->merge($posts);
$feed->sortByDesc('created_at');
The problem is that they do get merged together, but the sort function seems to not work. instead of them being mixed together they come in parts. so all the $friendPosts
posts come and the other posts come after wards
I'm using slim framework along with twig and eloquent. here's the entire controller that this is being used in, just for some context:
public function getSessionProfile($request, $response)
{
//return to sign in if not signed in
if ($_SESSION['user'] == null) {
return $this->view->render($response, 'templates/signin.twig');
}
//grab current user
$user = User::where('id', $_SESSION['user'])->first();
//grab the user's followers
$followers = Follow::where('follower_id', $user->id)->get();
//user posts
$posts = $user->posts;
//get the posts made by friendllowers
foreach ($user->follows as $follow) {
$follow = User::where('id', $follow->follower_id)->first();
//posts by people that user is following
$friendPosts = $follow->posts;
}
//append author to each post made by friendllowers
$friendPosts->map(function ($post) {
$postAuthor = User::where('id', $post->user_id)->first();
$post['authorName'] = $postAuthor->name;
$post['authorPicture'] = $postAuthor->avatar;
return $post;
});
//append an author to each post made by user
$posts->map(function ($post) {
$postAuthor = User::where('id', $post->user_id)->first();
$post['authorName'] = $postAuthor->name;
$post['authorPicture'] = $postAuthor->avatar;
return $post;
});
$feed = $friendPosts->merge($posts);
$feed->sortByDesc('created_at');
$this->container->view->getEnvironment()->addGlobal('User', $user);
//posts by user
$this->container->view->getEnvironment()->addGlobal('Posts',$user->posts);
//feed
$this->container->view->getEnvironment()->addGlobal('Feed',$feed);
// TODO: make two twig templates one for user only one for feed
$this->container->view->getEnvironment()->addGlobal('Followings', $user->follows);
$this->container->view->getEnvironment()->addGlobal('Followers', $followers);
return $this->view->render($response, 'home.twig');
}
I fixed the problem:
needed to change $feed->sortByDesc('created_at');
to
$feed = $feed->sortByDesc(function($post)
{
return $post->created_at;
});