Communication "many-to-many". How to display related data?

In the database there are two tables and organized connection between them belongsToMany ("many-to-many") through a staging table, for example, users (Users), groups (Community) and the junction table group_user.

How do I display a list of checkbox-owls all Communities of the site, with a marked checkbox-AMA, for a specific User, if he is in the community.

Did so, but this option does not work correctly

@foreach ($groups as $group)
 @foreach (@user->groups as $user_group)
 @if ($user_group->id == $group->id)
 <input type="checkbox" checked>$group->title
@else
 <input type="checkbox">$group->title
@endif
@endforeach
@endforeach


Cycle in a loop and then test the condition as it is not very much.
Maybe there is some method that would simplify the check of one model to another? He still can't understand(
August 19th 19 at 23:04
3 answers
August 19th 19 at 23:06
Solution
@foreach ($groups as $group)
 @if ($user->groups->contains($group))
 <input type="checkbox" checked>{{ $group->title }}
@else
 <input type="checkbox">{{ $group->title }}
@endif
@endforeach
Just what you need! Thank you! - wilfredo commented on August 19th 19 at 23:09
August 19th 19 at 23:08
@foreach ($groups as $group)
 @if (in_array($group, @user->groups))
 <input type="checkbox" checked>$group->title
@else
 <input type="checkbox">$group->title
@endif
@endforeach
$user->groups, $group - is objects, in_array works, as I understand, with massively (in_array() expects parameter 2 to be array, object given). To convert the object into an array, I think it's not the best solution - wilfredo commented on August 19th 19 at 23:11
August 19th 19 at 23:10
This should be done at the DB level

SELECT * FROM users u 
LEFT JOIN group_user gu ON (u.user_id = gu.user_id) 
LEFT JOIN group g ON (g.group_id = gu.group_id)
WHERE g.group_id = group_id
But we need to show all the existing groups and to mention only those, which belongs to the user - wilfredo commented on August 19th 19 at 23:13

Find more questions by tags DatabasesLaravelSQL