简体   繁体   中英

Get posts by followers laravel

I want to display a feed page for an authenticated user which shows the latest posts from users that they follow. I have a follow system set up already which has the following:

Tabels:

  • Posts
  • users
  • follow

User model:

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

Feed controller:

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

This is pulling in the posts from the users a user follows but, i have a problem. The foreach is returning a user and then their posts each time.

What its doing now:

Followed user 1

  • Post 1
  • Post 2
  • Post 3 etc etc

Followed user 2

  • Post 1
  • Post 2
  • Post 3 etc etc

What i would like to display:

  • Followed User 1 Post 1
  • Followed User 2 Post 1
  • Followed User 2 Post 2
  • Followed User 1 Post 2 etc etc

Any ideas?

<?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();
        }

First, you need to get the users that the current user follows and their ids so you can store it in $userIds .

Second, you need the feed to also contain your posts, So you add that to array too.

Third, You return the posts where the poster or author of that post is in that array that we got from the first step.

And grab them store them from newest to oldest.

Any questions are welcome!

Just a correction for Akar 's answer:
For those who are here in 2020, instead of lists you must use pluck . it changed in newer versions of laravel.

public function getFeed(User $user) 
        {
            $userIds = $user->following()->pluck('user_id');
            $userIds[] = $user->id;
            return \Post::whereIn('user_id', $userIds)->latest()->get();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM