Skip to content
Advertisement

Laravel :: Best way to update a foreign key

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(); 
});

and I want to update to make it ->onDelete(‘cascade’);

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

What is the best way to do this?

Is there something like ->change();

Thanks

Advertisement

Answer

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');
    });
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement