How to check if foreign key exists in laravel

To check foreign key exists in laravel is a common issue working with the foreign key when we need to delete them using the migration file, but if it doesn’t exists then the code execution gives error

SQLSTATE[HY000]: General error: 1828 Cannot drop column 'table_column_id': needed in a foreign key constraint 'table_table_column_id_foreign' (SQL: alter table `table` drop `table_column_id`)

I was using the simple command for dropping the foreign key but missed checking them step.

Here are the common function I have created using with the  help of article here.

use Illuminate\Support\Facades\Schema;

function hasForeignKey(string $table, string $column): bool
{  
    $fkColumns = Schema::getConnection()
        ->getDoctrineSchemaManager()
        ->listTableForeignKeys($table,$dbName);

    return collect($fkColumns)->map(function ($fkColumn) {
        return $fkColumn->getColumns();
    })->flatten()->contains($column);
}

Now, you can check if your foreign key exists in laravel table in your current database table using the function hasForeignKey('table_name','column_id'). It will give you the boolean response ( true/false ).

To get to know more about other Laravel topics, you can check these articles too.

 

Please follow and like us:

Related Posts

Leave a Reply

Share