Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning checked checkboxes based on pivot table

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!

like image 294
trh88 Avatar asked Jul 23 '26 15:07

trh88


2 Answers

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
like image 187
trh88 Avatar answered Jul 25 '26 04:07

trh88


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
like image 21
The Alpha Avatar answered Jul 25 '26 06:07

The Alpha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!