-1

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

  • 2
    Don't use `->get()` together with `->find()` – brombeer Apr 29 '21 at 16:11
  • This question is asked _a lot_ on Stackoverflow. One of these duplicates should help you: [Property \[title\] does not exist on this collection instance](https://stackoverflow.com/questions/41366092/property-title-does-not-exist-on-this-collection-instance), https://stackoverflow.com/questions/46846225/property-name-does-not-exist-on-this-collection-instance, https://stackoverflow.com/questions/43320223/property-id-does-not-exist-on-this-collection-instance or https://stackoverflow.com/questions/57782097/property-subcategory-does-not-exist-on-this-collection-instance – Tim Lewis Apr 29 '21 at 16:58

2 Answers2

0

Actually, you can achieve this with one line if you use eloquent smart:

$user = User::find($user_id);
$posts = Post::whereIn('users_id', $user->friends()->pluck('id'))->get()

return $posts;

If the $user_id is auth user then you can use this as well:

$posts = Post::whereIn('users_id', auth()->user()->friends()->pluck('id'))->get()
Dharman
  • 30,962
  • 25
  • 85
  • 135
ibrahim-dogan
  • 621
  • 1
  • 5
  • 14
0

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

Aless55
  • 2,652
  • 2
  • 15
  • 26