What do you mean extract; do you want only the "primary" groups for the authenticated user, or do you want to append a property on the Group instances?
Mar 12, 2021
3
Level 1
How to add many-to-many pivot collumn to collection directly?
I have 3 tables users, groups and group_user
group_user have an extra value named is_primary
so inside my User model I have:
public function groups(){
return $this->belongsToMany('App\Models\Group')->withPivot(['is_primary']);
}
Now inside my controller I need to extract the groups with the is_primary field so I'm doing this:
$groups = Auth::user()->groups;
foreach ($groups as &$group) {
$group['is_primary'] = $group->pivot->is_primary;
}
I am almost sure that there is a much better way to do that on a single line of code. I just can't find how. any idea?
Please or to participate in this conversation.