Search code examples
laraveleloquent-relationship

Property [posts] does not exist on this collection instance laravel


I have three tables

Users
   id  name   email
friends
   id   user_id   friend_id
Posts 
   id   image    users_id 

I want to show all posts of login user and of his all friends . to get post of login user I done that

$user_id=Auth::user()->id;
$data=User::find($user_id)->posts;

But not able to get posts of all friends I tried this

$friend_id = [];
$friends=User::find($user_id)->friends;  //get all friends it returns like that [2,3]
  foreach ($friends as $friend) {
    $friend_id[]=$friend->friend_id;
  }
  $data=[];
  foreach($friend_id as $friend)
  {
    $data[]=User::find($user_id)->get()->posts;
  }

return $data;

but it gives me that error

Property [posts] does not exist on this collection instance.

Is there any escape from that issue


Solution

  • You first have to get your user: $user = Auth::user();

    The users friends (better their ids) can be retrieved like this:

    $friend_ids = $user->friends()->pluck('id')

    Afterwards you will need to add the id of the current user to the id array:

    $all_ids = array_push($friend_ids, $user->id)

    Lastly you can retrieve all posts:

    $posts = Posts::whereIn('user_id', $all_ids)->get();