简体   繁体   中英

How to update related table in Laravel?

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?

You shouldn't use update. Use the sync method:

$student->hobbies()->sync($request->hobby);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM