How to access the contents of this collection in laravel / php

I am new to Laravel and am doing a project to create an application for a mini-social network. I have a publishing model that has a relationship with the user model. I have a Mail page where only messages from an authenticated user and his friends will be shown. In my PostController, I requested from friends of an authenticated user the following:

$friends = Auth::user()->friends(); 

If the friends () object was previously defined in my friend tag. This works well, as shown in the screenshot. I tried to request messages whose user_id is the user or friends user id, e.g.

 $posts = Post::where('user_id', $user->id) ->where('user_id', $friends->id) ->get(); 

but keep getting the error message

The [id] property does not exist in this collection instance ...

The collection is shown as being reset on the screen. How can I iterate and get an array of identifiers of all friends. enter image description here

enter image description here

0
source share
1 answer
 $friends = Auth::user()->friends(); 

now $friends is a set containing a set of users, note that $friends does not contain a variable named id , and each element in the collection (User object) contains an identifier.

Here you get an error - ->where('user_id', $friends->id) (here $friends does not have an identifier)

So, first we take out all the sheets of friends, and then we take the messages that are made by friends.

 $friends = Auth::user()->friends(); $friends_id = $friends->pluck('id'); //we have all friends id as an array $posts = Post::where('user_id', $user->id) ->whereIn('user_id', $friends_id) ->get(); 
+1
source

Source: https://habr.com/ru/post/1275312/


All Articles