I have 3 tables:
doors
- id
- name
- image
colors
- id
- name
- image
door_colors
- id
- door_id
- color_id
and 2 models with a many-to-many relationship (each door comes in a variety colors, and many colors overlap door-to-door):
Door Model
class Door extends Eloquent {
public function colors()
{
return $this->belongsToMany('Color', 'door_colors');
}
}
Color Model
class Color extends Eloquent {
public function doors()
{
return $this->belongsToMany('Door', 'door_colors');
}
}
I want to create a form where I can edit the door, and update the available colors via checkboxes. This is my Admin Doors Controller
class AdminDoorsController extends AdminController {
public function edit($id)
{
$data['door'] = Door::find($id);
$data['colors'] = Color::all();
return View::make('admin/doors/form', $data);
}
}
and the Admin Doors Form View
{{ Form::model($door) }}
Colors:
@foreach ($colors as $color)
{{ Form::checkbox('colors[]', $color->id) }} {{ $color->name }}
@endforeach
{{ Form::close() }}
Question 1: How do I make it so that as the checkboxes are outputted, the ones with an existing relationship with the current door are checked and the ones without are unchecked.
Question 2: Once I check the boxes and hit submit, how would I update the relationships? $door->colors()->detach();
to clear all existing ones for this door, then $door->colors()->attach($color_id_array);
to create new ones based on an array of color ids?
Any input is appreciated!