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

Deadly 提交于 2019-12-04 06:23:54

问题


I am new to Laravel and doing a project to build a mini-social network app.I have a post model that has a relationship with the user model. I have a Post page, where only the posts of the authenticated user and his/her friends will show. In my PostController, i queried for the friends of the authenticated user like so;

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

Where the friends() object has earlier been defined in my friendable trait. That works well as shown in the screen shot. I tried to query for the posts whose user_id is that of the authenticated user or that of the friends, like so

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

but keep getting an error

Property [id] does not exist on this collection instance…

The collection is shown as die-dumped on the screen-shot. How can I iterate over and get an array of the id’s of all the friends.


回答1:


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

now the $friends is a collection, which contains a collection of users, please note that $friends does not contain a variable named id rather the each item in collection(The User object) contains an id.

This is where you get the error - ->where('user_id', $friends->id)(here $friends have no id )

so first we take out all the ids of friends, and then take the posts which are made by the 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();


来源:https://stackoverflow.com/questions/48410126/how-to-access-the-contents-of-this-collection-in-laravel-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!