mercredi 20 mai 2015

Laravel 5 checkbox pivot table data

Got a ManyOnMany system (3 tables, projects, users, project_user)

Many users can work on a project, and a user can have many projects.

When checkbox = checked it sends the database to the pivot table.

Now I'm facing the problem that everytime I click the project/user id will get send to the project_user table. And I need to have the checkbox already checked when the user is actually added to the project.

Blade:

@foreach($users as $user)
            <tr>
                <td>
                    {{$user->firstname}} {{$user->middlename}} {{$user->lastname}}
                </td>
                <td>
                    <input name="contribute[{{$user->id}}]" type="checkbox" value="1"/>
                </td>
            </tr>
        @endforeach

Controller:

public function update(CreateProjectRequest $request)
{
    if($request->get('contribute'))
    {
        foreach($request->get('contribute') as $k => $contribute)
        {
            if($contribute == 1)
            {
                $project = $this->project->find($request->project_id);
                $project->users()->attach($k);
            }
        }
    }

    $project = $this->project->find($request->project_id);
    $project->fill($request->input())->save();

    return redirect('project');
}




Aucun commentaire:

Enregistrer un commentaire