Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 686
John Avatar asked Feb 22 '15 00:02

John


2 Answers

<?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!

like image 156
Akar Avatar answered Nov 02 '22 11:11

Akar


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

like image 40
Pooria Honarmand Avatar answered Nov 02 '22 12:11

Pooria Honarmand