Inserting and deleting many to many relationships in laravel

Inserting and deleting many to many relationships in core PHP can be a headache and have to loop through each record to insert and delete. But in laravel, it is really simple.

Laravel Eloquent come with additional helpers to make it working. For example, a course can have many schools and a school can have many courses and to store and delete a course to a school in intermediate table that joins both models, use attach/detach method.

First, you need to define many to many relationships in your model. Click below to view.
Defining many to many relationships in laravel

// get course 
$course = Course::findOrFail($id); 
// Delete all schools for course
$course->schools()->detach();
// Insert all schools for course
$course->schools()->attach($school_ids);

Author: Anees Ahmad

Anees Ahmad is a young co-founder, creative project manager and multi-talented web developer at Techstriders.