哪个是关于在Laravel中删除行和插入行的最佳方法

As title, I have a table like student and another table is class. User can edit about student having some class. There is one to many relationship. When user edit student's class, I always must to delete this student's class. And insert the new class after that.

\App\class:where('student_id',$student->id)->delete();
foreach($request->input('class') as $class){
  $new = new \App\class;
  $new->student_id = $student->id;
  $new->class_id = $class;
  $new->save();
}

Is there have any solution about this issue? Thanks.

For the moment I'll assume you have your relationships setup properly.

You'll want to take a look at sync.

Documentation

$student->classes()->sync($request->input('class'))

The sync method want's the ID's of the classes as argument.