Answer the question
In order to leave comments, you need to log in
Relationship "many-to-many". How to display related data?
There are two tables in the database and an organized relationship between them belongsToMany ("many-to-many") through an intermediate table, for example, users (Users), groups (Communities) and a linking table group_user.
How can I display a list of checkboxes of all Communities on the site, with checkboxes checked, for a specific User, if he is a member of the community.
I did this, 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
Answer the question
In order to leave comments, you need to log in
@foreach ($groups as $group)
@if ($user->groups->contains($group))
<input type="checkbox" checked>{{ $group->title }}
@else
<input type="checkbox">{{ $group->title }}
@endif
@endforeach
@foreach ($groups as $group)
@if (in_array($group, @user->groups))
<input type="checkbox" checked>$group->title
@else
<input type="checkbox">$group->title
@endif
@endforeach
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question