Many-to-Many Eloquent relationship update with Laravel Form Model Binding & Checkboxes Many-to-Many Eloquent relationship update with Laravel Form Model Binding & Checkboxes laravel laravel

Many-to-Many Eloquent relationship update with Laravel Form Model Binding & Checkboxes


Question 1: You should pass this into the view that contains your form, though it can also go right in the view, though that's not really best practice. Do something similar to this...

$checkeds = Door::find(1)->colors()->lists('id');

...where the door you are finding is the door that's being updated. Then before you output the checkbox in the loop, add

$checked = in_array($color->id, $checkeds) ? true : false;

Then you would change

{{ Form::checkbox('colors[]', $color->id) }} {{ $color->name }}` 

to

{{ Form::checkbox('colors[]', $color->id, $checked) }}{{ $color->name }}

Question 2: There is actually a perfect method given to you for this. Use

$door->colors()->sync(Input::get('colors'));

It will both delete the old ones and add all the new ones in one shot.


Suppose you are modeling user and role and want to edit user with roles.

In your controller edit,

$user = User::find($id);$roles = Role::lists('name', 'id'); // to populate all roles

In your template if you use select,

{{ Form::select('roles[]', $roles, array_pluck($user->roles, 'id'), ['multiple']) }}

In your controller update,

$inputs = Input::all();$roles = $inputs['roles'];$user->roles()->sync($roles);// $user->fill($inputs);// $user->save();