V
V
Vasyl Fomin2017-01-30 00:27:58
Laravel
Vasyl Fomin, 2017-01-30 00:27:58

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

The loop in the loop and then checking the condition is somehow not very pleasant.
Maybe there is some method that would make it easier to check if one model belongs to another? I still can't figure it out myself

Answer the question

In order to leave comments, you need to log in

3 answer(s)
T
Taras Fomin, 2017-01-30
@fomvasss

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

A
anton_lazarev, 2017-01-30
@anton_lazarev

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

M
marrs, 2017-01-30
@marrs

This must be done at the database 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

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question