Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

HOVO's avatar
Level 1

Cascade on delete not working

Hello everyone i have 2 tables users and roles i use many to many relationship and they have role_user pivot table need when some role will be deleted users who have that role will be deleted too onDeleted method not working what i am doing wrong ??? here is my code

    Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

 Schema::create('roles', function (Blueprint $table) {
            $table->id();
            $table->string('role');
            $table->timestamps();
        });

  Schema::create('role_user', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->unsignedBigInteger('role_id');
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->timestamps();
        });

User model

 public function roles(){
        return $this->belongsToMany(Role::class)->withTimestamps();
    }

Role model

  public function users(){
        return $this->belongsToMany(User::class)->withTimestamps();
    }

THANKS :3

0 likes
2 replies
MichalOravec's avatar
Level 75

It removes only data from role_user table. And not users which have that role.

sr57's avatar

Take this line : $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

If you delete an id from the table users it'll delete the record with the key user_id from the table role_user.

With this, you should be adpat your model as you want.

Please or to participate in this conversation.