0

Laravel 7.x

I need to get posts from two relations. Look:

User has Posts;

User has Friends (accessor);

Friends has Posts;

How can I get all own (User) posts and all posts by each Friend, and paginated?

Which the best way to do that?

Only to pass the idea that I want to say:

$user = User::find(1);
$posts = $user->with('posts','friends.posts')->paginate(15); // I wanna get only the Posts collection
STA
  • 30,729
  • 8
  • 45
  • 59

2 Answers2

1

I would suggest query your Post model and then apply filter for user and related friends filter.

$user = User::with('friends')->find(1);
$userIds = $user->friends->pluck('id')->toArray();
array_push($userIds, $user->id);
$posts = Post::whereIn('user_id', $userIds)->paginate(15);
M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118
  • 1
    That's the way I was going to do it. But I would very much like to use the relationships of the eloquent. Anyway, that works. – morphinduction Aug 17 '20 at 17:54
1

You can use hasManyThrough, this relationship is a bit complicated to understand a provide shortcut way to access data of another mode relation.
In your User model make relationship like this way :

public function posts()
{
   return $this->hasManyThrough(
     Post::class,
     Friend::class,
     'user_id', // Foreign key on friends table...
     'friend_id', // Foreign key on posts table...
     'id', // Local key on users table...
     'id' // Local key on friends table...
   );
}

Now you can get all posts from User model like this way :

$user = User::find(1);
$posts = $user->with('posts')->paginate(15); 
STA
  • 30,729
  • 8
  • 45
  • 59
  • So... look my scenario: I have a User model, This represents a user. The relationship with another user is made with accessor (getFriendsAttribute). $user->friends returns my confirmed friends. The friends also are User. The User model has a posts method that returns all posts from that user. I think that accessor is the problem. – morphinduction Aug 17 '20 at 17:50