Get posts by followers laravel

eloquent, laravel, laravel-4, model, php

Solution

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

Problem

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?

Original source