mercredi 20 mai 2015

Laravel - Sending data to pivot table using a checkbox

I have 3 tables : projects - users - project_user.

This is a ManyOnMany relation so that's why I have a pivot table.

I got them linked via my model using belongsToMany.

Now comes my problem.

I have a table like this: enter image description here

So I have a project selected, and a table with my users with active/contribute checkboxes. When the active/contribute checkbox is checked the user will be linked to the project.

So in my head I have something like this:

When the checkbox is checked, it needs to send the user_id including the $this->project_idto the pivot table project_user so it will link the project <->user.

But now the problem is that I have no clue how I'm going to get this into working code

HTML/Blade:

@foreach($users as $user)
<tr>
    <td>
        {{$user->firstname}} {{$user->middlename}} {{$user->lastname}}
    </td>

    <td>
        <input name='contribute' type='hidden' value='0'>
            {!! Form::checkbox('', '1', false) !!}
    </td>
</tr>
@endforeach

Model:

User

public function projects() 
{
    return $this->belongsToMany('App\Project', 'project_user', 'user_id', 'project_id');
}

Project

public function users()
{
   return $this->belongsToMany('App\User', 'project_user', 'project_id', 'user_id');
}

Controller:

public function edit($id, Project $project)
{
    $users = User::all();

    $project = $this->project->find($id);

    return view('project.edit', ['project' => $project, 'id' => 'edit'], compact('users'));
}

public function update(CreateProjectRequest $request, $project)
{
    $project = $this->project->find($project);
    $project->fill($request->input())->save();

    return redirect('project');
}

Tell me if any other code is needed to be provided




Aucun commentaire:

Enregistrer un commentaire