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:
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
Followed user 2
What i would like to display:
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With