Zia Yamin
Zia Yamin

Reputation: 1004

How to update one to many relationship in laravel?

I have a problem with updating the following table

enter image description here

And the data come from the view like below

enter image description here this is my code

 foreach ($request->input('class_teacher') as $key=>$value){
                $class_teacher =ClassTeacher::where('class_id',$id);
                $class_teacher->class_id = $classes->class_id;
                $class_teacher->teacher_id =$value;
                $class_teacher->save();
            }

after the update I want it to be like this one

enter image description here

Upvotes: 1

Views: 652

Answers (1)

mohammad mortezaie
mohammad mortezaie

Reputation: 24

First delete the relationships, then recreate them all again.

 ClassTeacher::where('class_id',$id)->whereIn('teacher_id', $request->input('class_teacher'))->delete();
  
  foreach ($request->input('class_teacher') as $key=>$value){
    $class_teacher =new ClassTeacher;
    $class_teacher->class_id = $classes->class_id;
    $class_teacher->teacher_id =$value;
    $class_teacher->save();
  

Upvotes: 1

Related Questions