I have a question about migrations in Laravel. Is it possible to handle foreign keys with a simple if statement? Specifically, I want to ensure that if a foreign key already exists, it should not be migrated again. Is there a straightforward way to do this?
This is my code for example.
if (Schema::connection('orders_import')->hasTable('mymuesli_label')) {
Schema::connection('orders_import')->table('mymuesli_label', function (Blueprint $table) {
$table->foreign(['roll'], 'roll_id')->references(['id'])->on('mymuesli_roll');
});
}
if (Schema::connection('orders_import')->hasTable('parameter_mapping')) {
Schema::connection('orders_import')->table('parameter_mapping', function (Blueprint $table) {
$table->foreign(['customer'], 'parameter_mapping_fk_customer')->references(['id_customer'])->on('customer');
});
}
if (Schema::connection('orders_import')->hasTable('product_mapping')) {
Schema::connection('orders_import')->table('product_mapping', function (Blueprint $table) {
$table->foreign(['customer'], 'product_mapping_fk_customer')->references(['id_customer'])->on('customer');
});
}
2
Answers
I believe yes, but with laravel 11. With
Schema::getForeignKeys('your_table')
. I will do an example for your first code:ps: This method gives you an array of arrays with
name
(string) andcolumns
(array of strings), and you need to get it right with the migration->foreign($columns, $name)
.I think this will be the straightforward method with an if statement.
Here is your updated migration code.
Just use If(!Schema->hasColumn(‘table_name’, ‘column_name’))
This method has two parameters, hasColumn(‘table_name’, ‘column_name’)