KD_Raj
KD_Raj

Reputation: 337

Laravel 7 Migration - Foreign Key created but its constraint code not working

I cannot seem to figure out why my PK and FK of the same exact type are not linked in Laravel. Both tables are InnoDB. The foreign key in the second screenshot shows that I can enter any integer even if if does not exist in the PK table. Please help. My code for the FK creation migration is below:

Proof that both PK and FK are same type (Meeting table on the left; Participant table on the right: Proof that both PK and FK are same type

Proof that the Integrity Constraint can be broken ( I can enter 9999999 etc. I should only be able to enter 1, 2 or 3 as FK IDs): Proof that the Integrity Constraint can be broken:

Migration file:

  <?php
    
    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;
    
    class CreateParticipantsTable extends Migration
    {
        public function up()
        {
            
            Schema::create('participants', function (Blueprint $table) {
    
                $table->id();
                $table->unsignedBigInteger('meeting_id')->nullable();
                $table->string('attendance');
                $table->string('invited');
    
    
                $table->foreign('meeting_id')
                ->references('id')
                ->on('meetings')
                ->onDelete('cascade');
    
                $table->timestamps();
               // $table->engine = "InnoDB";
    
            });
        }
    
     
        public function down()
        {
            Schema::dropIfExists('participants');
        }
    }

Upvotes: 0

Views: 255

Answers (1)

KD_Raj
KD_Raj

Reputation: 337

I figured it out. In the /config/database.php file you have to set the storage engine for the database before tables are created. What's weird is I was changing the storage engine for the database after I created some other tables before and did not have any issues:

'engine' => null,

to

'engine' => 'InnoDB',

Upvotes: 1

Related Questions