Reputation: 4222
I am using Laravel 5.3
.
How to update related table in Laravel?
There are 2 tables,students
and hobbies
, they have many-to-many relations.
In view,hobbies are checkboxes,like this:
<input class="form-check-input" type="checkbox" name="hobby[]" value="1" > basketball
<input class="form-check-input" type="checkbox" name="hobby[]" value="2" > football
<input class="form-check-input" type="checkbox" name="hobby[]" value="3" > swimming
In controller,store()
method is like this,it can work:
public function store(Request $request)
{
$student=Student::create($request->except('hobby'));
$student->hobbies()->attach($request->hobby);
return redirect()->action('StudentController@index');
}
update()
method is like this,hobbies can not be updated:
public function update(Request $request, $id)
{
$student = Student::findOrFail($id);
$student->update($request->except('hobby'));
//How to update hobbies?
$student->hobbies()->attach($request->hobby);
return redirect()->action('StudentController@show', ['id' => $id]);
}
How to update hobbies?
Upvotes: 0
Views: 440
Reputation: 365
You shouldn't use update. Use the sync
method:
$student->hobbies()->sync($request->hobby);
Upvotes: 3