Home > OS >  How do i get my cascadeOnDelete to work in laravel
How do i get my cascadeOnDelete to work in laravel

Time:11-14

Trying to learn Laravel, i am following a tutorial from laracast called Laravel 8 from scratch and has now reached episiode about cascades https://laracasts.com/series/laravel-8-from-scratch/episodes/53

I'm not getting any errors but if i add a comment to a post, and then delete the post then my comment stays in the database, while his is removed with the post. I tried deleting the post using laravel, but also using tableplus. My setup is a bit diffrent from his so i'm wondering if my cascades arent working because of something in my setup.

comment migration

Schema::create('comments', function (Blueprint $table) {
        $table->id();
        $table->foreignId('post_id')->constrained()->cascadeOnDelete();
        $table->foreignId('user_id')->constrained()->cascadeOnDelete();
        $table->text('body');
        $table->timestamps();
    });

Post migration

Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->foreignId('user_id');
        $table->foreignId('category_id');
        $table->string('slug')->unique();
        $table->string('title');
        $table->text('excerpt');
        $table->text('body');
        $table->timestamps();
        $table->timestamp('published_at')->nullable();
    });

I've also tried using $table->foreignKey('post_id')->references('id')->on('posts')->onDelete('cascade) but i cant seem to get it working.

I have also tried adding the constrain my self at the mySql database using

alter table
   `comments`
add
   constraint `comments_post_id_foreign` foreign key (`post_id`) references `posts` (`id`) on 
delete cascade

Do i need a specific use, or could it be my setup? php/database setup versions from wamp

CodePudding user response:

I think if you search for myisam and innodb, you will probably find the answer. in myisam, foreign keys are not deleted

  • Related