I have a reminder table that has a one to many relation on itself,
so i have this table:
id: primary key
reminder_id: my foreign key to reminder table
so that i could have a record with key id=1
, and many other records that refers to it with reminder_id=1
.
I also have a user table, with his id, and a reminder_user to hanlde many to many relationship.
The relation are working good, so that from the user i can retrieve his reminders, from a reminder his children reminder and so on.
The Reminder model:
class Reminder extends Model {
public function users() {
return $this->belongsToMany("App\Models\User");
}
public function reminder() {
return $this->belongsTo("App\Models\Reminder");
}
public function reminders() {
return $this->hasMany("App\Models\Reminder");
}
}
The user model:
class User extends Authenticatable
{
use Notifiable;
public function reminders() {
return $this->belongsToMany("App\Models\Reminder");
}
}
My problem is that when i update a reminder, the record in my pivot table reminder_user are not deleted.
i tried to create this observer:
namespace App\Observers;
use App\Models\Reminder;
class ReminderObserver {
public function deleting(Reminder $reminder)
{
$reminder->users()->detach();
}
}
and added it to the appservice provider:
public function boot()
{
//...
Reminder::observe(ReminderObserver::class);
}
but, so far, the records in reminder_user table are not being deleted when i do this transaction:
DB::transaction(function()use($reminder, $repeated, $user) {
//delete old reminders
$reminder->reminders()->delete();
//add many new reminders
$reminder->reminders()->saveMany($repeated);
//save new relation with user
$user->reminders()->saveMany($repeated);
//update current reminder
$reminder->save();
});
update
As from the answer, the problem is that calling delete() on the query builder doesn't trigger the model observers.