Search code examples
laravelrelationshipeloquent-relationship

Laravel Bulk Detach


First, I use detach() in laravel with this approach and this is work!

$student = \App\StudentRegistrars::withTrashed()->findOrFail($id);
$student->father_registrars()->detach();
$student->mother_registrars()->detach();  

But when I am trying to mass detach in laravel, I can't do that.

$students = \App\StudentRegistrars::whereIn('id', $ids);
$student->father_registrars()->detach();
$student->mother_registrars()->detach(); 

Any solution about this problem?


Solution

  • There's quite a few issues with your code. You're close, but not quite there.

    First, you need to be aware of what your variable is. Currently, this is not working, as $student is not defined. You called your variable $students (with an 's'), so make sure you're using the right variable.

    Secondly, at the point you're calling detach(), your $students variable is an instance of the Builder class, not a single StudentRegistrars instance. You need to finalize your query with a closure:

    $students = \App\StudentRegistrars::whereIn('id', $ids)->get();
    

    Thirdly, the detach() method only works on a single instance, so if you called $students->father_registrars()->detach(), it would still fail.

    You need to iterate your results and call detach() one-by-one:

    foreach ($students as $student) {
      $student->father_registrars()->detach();
      $student->mother_registrars()->detach(); 
    }
    

    You final code would therefore be:

    $students = \App\StudentRegistrars::whereIn('id', $ids)->get();
    foreach ($students as $student) {
      $student->father_registrars()->detach();
      $student->mother_registrars()->detach(); 
    }
    

    There are more efficient approaches to mass detachment, such as directly querying and deleting records from the pivot table (or tables):

    DB::table('pivot')->whereIn('column', $ids)->delete();
    

    But this answer serves to fix your logic issues.