Alias Alias - 1 month ago 10
SQL Question

Laravel foreign key onDelete('cascade') not working

I have a many-to-many relationship between User & Role, with a role_user table. My migrations are setup as so (simplified):

users
table:

public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('email')->unique();
});
}


roles
table:

public function up()
{
Schema::create('roles', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
});
}


role_user
table:

public function up()
{
Schema::create('role_user', function(Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->integer('role_id')->unsigned();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
});
}


So as per the docs, I set my foreign keys to unsigned.

Now, I add a couple of users, and attach some roles - everything works fine. However, when I delete a user (
User::destroy(2)
) the rows for that user in the
role_user
table do not get deleted, which is causing redundant rows.

What am I doing wrong?


  • MySQL + InnoDB



EDIT: Grabbing the model and applying
->delete();
also has the same effect.

Answer

Try setting when trying to create this table. This fix has worked for me.

$table->engine = 'InnoDB';

I have filed a bug under: https://github.com/laravel/framework/issues/8730

Comments