skip to Main Content

My Laravel App is creating all tables in migrations successfully but it’s failing to create a foreign keys relationships in the table or even enforce cascade when I delete the primary record.
Here is the migration.

    Schema::create('articles', function (Blueprint $table) {
        $table->id('id');
        $table->unsignedBigInteger('user_id');
        $table->string('title');
        $table->text('excerpt');
        $table->text('body');
        $table->timestamps();

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

    });

When I run php artisan migrate it’s migrating successfully.

λ php artisan migrate

Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table (0.11 seconds)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table (0.1 seconds)
Migrating: 2019_08_19_000000_create_failed_jobs_table
Migrated:  2019_08_19_000000_create_failed_jobs_table (0.07 seconds)
Migrating: 2020_08_26_122846_create_articles_table
Migrated:  2020_08_26_122846_create_articles_table (0.14 seconds)

But, when I check the database, the relationship is not getting created, just and index for foreign key.
Check the Articles Table image in this link. I have marked the necessary parts

Check the Users Table image here. I have highlighted the primary key.

I have added some factory data relating the user and article and when I delete the user, the articles are being left as orphans.

What could be wrong?

  • PHP Version: 7.3.21
  • MySql Version: 5.7.31
  • MariaDB Version: 10.4.13
  • Laravel Framework Version: 7.25.0

Thank-you in advance.

2

Answers


  1. Chosen as BEST ANSWER

    The question has been answered in the comment by @ShakilAhmmed here

    All I did was go to config folder then database.php and change mysql database engine from null to innoDB i.e. From:

    //...
    'engine' => null,
    //...
    

    To:

    //...
    'engine' => 'InnoDB',
    //...
    

  2. You’re using Schema::create for creating the tables.

    In the Laravel docs, I see Schema::table when working with foreign keys. Perhaps you should try to split your code:

    Schema::create('articles', function (Blueprint $table) {
        $table->id('id');
        $table->unsignedBigInteger('user_id');
        $table->string('title');
        $table->text('excerpt');
        $table->text('body');
        $table->timestamps();
    });
    
    Schema::table('articles', function (Blueprint $table) {
        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');
    
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search