Home > Back-end >  Specifying a name for a foreign key in Laravel migration when using the constrained() method
Specifying a name for a foreign key in Laravel migration when using the constrained() method

Time:10-07

Laravel 8, database migrations. I know I can use the long-form :

$table->foreign('really_long_table_name_id', 'foreign_key_name')->references('id')->on('really_long_table_name')->onUpdate('cascade')->onDelete('cascade');

to create a foreign key with a specific name where (as in my case) the name that Laravel would automatically generate via the constrained() method :

$table->foreignId('really_long_table_name_id')->constrained()->onUpdate('cascade')->onDelete('cascade');

would be too long and cause MySQL to complain.

Is it possible to use the constrained() method and specify the foreign_key_name, rather than let it be dynamically generated? As I'm struggling to see it in the documentation, or any SO searches.

CodePudding user response:

You can use the index method to update the name of the index.

$table->foreignId('really_long_table_name')
    ->constrained()
    ->cascadeOnUpdate()
    ->cascadeOnDelete()
    ->index('index_name');
  • Related