Reputation: 543
I'm trying to get the attributes of relation of relation, but I got problems, I don't know how do this...
CONTROLLER:
public function user($id) {
$user = UserProfile::where('friendly_url', '=', $id)->with('user', 'shares.links')->first();
foreach($user->getRelation('shares')->pluck('links') as $link) {
//HERE IS TO RETURN LINK ATTRIBUTES, EXAMPLE $link->id
dd($link);
}
}
dd($link)
Collection {#309 ▼
#items: array:1 [▼
0 => Link {#314 ▼
#attributes: array:14 [▼
"id" => 1
"title" => "Crianças índigo nascem em 2018"
]
return $link->id
Exception
Property [id] does not exist on this collection instance.
Upvotes: 2
Views: 1276
Reputation: 7420
You are getting a collection of links on response therfore you need to iterate one more time to get the attributes.
foreach($user->getRelation('shares')->pluck('links') as $link) {
$linksAttr = $link->map(function($li) {
retrun [
//here you can return link attributes
'linkId' => $li->id,
'linkTitle'=>$li->title
];
});
dd($linksAttr);
}
}
Upvotes: 1
Reputation: 163978
Since $link
is a collection, get an object with first()
:
dd($link->first()->id);
Upvotes: 0