phplaravellaravel-migrations

Changing a foreign key constraint in a Laravel migration


I have this migration file

Schema::create('table_one', function(Blueprint $table) 
{ 
    $table->increments('id'); 
    $table->string('name'); 
    $table->integer('table_two_id')->unsigned(); 
    $table->foreign('table_two_id')->references('id')->on('table_two'); 
    $table->timestamps(); 
});

I want to update to make the foreign key cascade on delete, as though I had run this:

$table->foreign('table_two_id')->references('id')->on('table_two')->onDelete('cascade');

How can I do this? Is there something like change() for foreign keys?


Solution

  • Drop the foreign key then add it again and run migrate.

    public function up()
    {
        Schema::table('table_one', function (Blueprint $table) {
            $table->dropForeign(['table_two_id']);
    
            $table->foreign('table_two_id')
                ->references('id')
                ->on('table_two')
                ->onDelete('cascade');
        });
    }