获取关注者的帖子 laravel

Get posts by followers laravel

我想为经过身份验证的用户显示一个提要页面,其中显示他们关注的用户的最新帖子。我已经设置了一个跟随系统,其中包含以下内容:

标签:

用户模型:

 public function follow() {  
    return $this->BelongsToMany( 'User', 'Follow' ,'follow_user', 'user_id');
}

进给控制器:

public function feed () {

    $user = (Auth::user());

        return View::make('profile.feed')->with('user',$user);

    }

Feed.blade

  @foreach ($user->follow as $follow)

 @foreach ($follow->posts as $post)

     //* post data here.

  @endforeach

 @endforeach

这是从用户关注的用户那里提取帖子,但是我遇到了问题。 foreach 每次都返回一个用户,然后返回他们的帖子。

现在在做什么:

已关注用户 1

已关注用户 2

我要显示的内容:

有什么想法吗?

<?php
        /**
         * Get feed for the provided user
         * that means, only show the posts from the users that the current user follows.
         *
         * @param User $user                            The user that you're trying get the feed to
         * @return \Illuminate\Database\Query\Builder   The latest posts
         */
        public function getFeed(User $user) 
        {
            $userIds = $user->following()->lists('user_id');
            $userIds[] = $user->id;
            return \Post::whereIn('user_id', $userIds)->latest()->get();
        }

首先,您需要获取当前用户关注的用户及其 ids,以便您可以将其存储在 $userIds

其次,您需要提要也包含您的 post,因此您也将其添加到数组中。

第三,你 return post 那个 post 的 posterauthor 在我们从第一个得到的数组中步骤。

并抓取它们,按从新到旧的顺序存储它们。

欢迎提问!

只是更正 Akar 的回答:
对于 2020 年来到这里的人,您必须使用 pluck 而不是 lists。它在 laravel.

的较新版本中发生了变化
public function getFeed(User $user) 
        {
            $userIds = $user->following()->pluck('user_id');
            $userIds[] = $user->id;
            return \Post::whereIn('user_id', $userIds)->latest()->get();
        }