laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 28 forks source link

Feature to check existence of index/foreign key #2527

Open calebeso opened 3 years ago

calebeso commented 3 years ago

Recently I pass throught a problem that I need to update a foreign key in a production database w/ Laravel 6, then I need to drop the already indexed column and change it to foreignkey instead of, and I was searching for a schema function that check the existence of it and then drop it, but I found nothing bout it. The solution for it was to implement this Trait to check the existence -> https://gist.github.com/Razoxane/3bc74900b4eb5c983eb0927fa13b95f5#gistcomment-2751037 And then call it in a migration, it works perfectly nice! But would be even nice if Laravel already have it implemented by itself!

The Trait.

<?php

namespace Migrations;

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

trait MigrationIndex
{
    public function _dropIndexIfExist($tableName, $indexName)
    {
        Schema::table($tableName, function (Blueprint $table) use ($tableName, $indexName) {
            $sm = Schema::getConnection()->getDoctrineSchemaManager();
            $doctrineTable = $sm->listTableDetails($tableName);

            if ($doctrineTable->hasIndex($indexName)) {
                $table->dropIndex($indexName);
            }
        });
    }

}