Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

fcolecumberri's avatar

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?

0 likes
3 replies
tykus's avatar

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?

fcolecumberri's avatar

when I said extract I meant retrieve (sorry English is not my first language).

I want to retrieve all the groups of the user and serialize the data to an API, but I want to include the is_primary field into the serialization.

tykus's avatar

In that case, this should work:

$groups = Auth::user()->groups
->map(function ($group){
	return tap($group, fn ($group) => $group->is_primary = (bool) $group->pivot->is_primary);
});

EDIT it would be remiss not to mention that you can do this easily in a query also:

$groups = Group::select(['is_primary', 'groups.*'])
  ->join('group_user', fn ($join) => $join->on('group_id', 'groups.id')->where('user_id', auth()->id()))
  ->get()

Please or to participate in this conversation.