This question is regarding Laravel and PHP.

I am building a form that allows users (players) to be assigned to / de-assigned from a team using checkboxes.

Many users can belong to many teams. I have a pivot table team_user to manage the many-to-many relationship.

I am having trouble populating the checkboxes based on whether the association exists in the pivot table.

So far I have them in two separate 'bits', which you can see below:

My Controller:

$users_checked = $team->users()->get();
$users = User::all();
return View::make('team/addplayers', compact('users', 'team', 'users_checked'));

My View:

@foreach ($users_checked as $user_checked)
    <p>
    {{ Form::checkbox('player[]', $user_checked->id, true) }}
    {{ Form::label('email', $user_checked->email) }}
    </p>
@endforeach

@foreach($users as $user)
    <p>
    {{ Form::checkbox('player[]', $user->id ) }}
    {{ Form::label('email', $user->email) }}
    </p>
@endforeach

What is the most sensible way to 'combine' these into one list, where the checkbox is ticked if the association exists in the pivot, or not ticked if it doesn't?

Many thanks for any help!

有帮助吗?

解决方案 2

I think you may try something like this:

$teams = Team::with('users')->get();
return View::make('team/addplayers', compact('teams'));

In your view:

@foreach ($teams as $team)
    @foreach ($team->users as $user)
        <p>
            {{ Form::checkbox(
                   'player[]',
                   $user->id,
                   (in_array($user->id, $team->users->fetch('id')) ? 1 : 0)
               )
            }}
            {{ Form::label('email', $user->email) }}
        </p>
    @endforeach
@endforeach

其他提示

The answers put me on the right track, thank you. My actual solution is below:

In my controller:

public function showAddPlayer(Team $team)
{
    $users = User::all();
    return View::make('team/addplayers', compact('users', 'team'));
}

In my view:

@foreach ($users as $user)
    <p>
        {{ Form::checkbox('player[]', $user->id, $team->users->contains($user->id)) }}
        {{ Form::label('email', $user->email) }}
    </p>
@endforeach
{{ Form::checkbox('player[]', $user->id,in_array($user->id, $users_checked->lists('id')) ? 1 : 0 ) }}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top