nizam0786's avatar

SQLSTATE[42000]: Syntax error or access violation: 1059 Identifier name ' ' is too long

Hi guys,

I am trying to add a foreign key to my database and the following error is returned.


   Illuminate\Database\QueryException  : SQLSTATE[42000]: Syntax error or access violation: 1059 Identifier name 'mother_haematological_disorder_type_mother_medical_history_id_foreign' is too long (SQL: alter table `mother_haematological_d
isorder_type` add constraint `mother_haematological_disorder_type_mother_medical_history_id_foreign` foreign key (`mother_medical_history_id`) references `mother_medical_history` (`id`) on delete cascade)

I think the problem is the auto generated primary key but I don't know how to set it.


   Schema::table('mother_haematological_disorder_type', function ($table){
            $table->uuid('mother_medical_history_id')->unique()->after('id');
            $table->foreign('mother_medical_history_id')->references('id')->on('mother_medical_history')->onDelete('cascade');
        });

any ideas?

thanks in advance.

0 likes
8 replies
ftiersch's avatar

Just add a second parameter to the foreign() method with the name of the key :)

5 likes
nizam0786's avatar

@FTIERSCH - Thank for the reply: I tried this and it didn't work :(


   Schema::table('mother_haematological_disorder_type', function ($table){
            $table->uuid('mother_medical_history_id')->unique()->after('id');
            $table->foreign('mother_medical_history_id', 'test_foreign')->references('id')->on('mother_medical_history')->onDelete('cascade');
        });

1 like
toby's avatar

Take a look at the API docs: foreign(string|array $columns, string $name = null), which means that you can define your own name.

Schema::table('mother_haematological_disorder_type', function ($table){
    $table->uuid('mother_medical_history_id')->unique()->after('id');
    $table->foreign('mother_medical_history_id', 'NAME_GOES_HERE')->references('id')->on('mother_medical_history')->onDelete('cascade');
});

1 like
nizam0786's avatar

@TOBY - I tired the following but the same error is being returned I am not exactly sure why? :(


   Schema::table('mother_haematological_disorder_type', function ($table){
            $table->uuid('mother_medical_history_id')->unique()->after('id');
            $table->foreign('mother_medical_history_id', 'name')->references('id')->on('mother_medical_history')->onDelete('cascade');
        });

nizam0786's avatar

I have also noticed it adds the foreign key to the database with the passed name however, it returns the error when running 'php artisan migrate:fresh' ???

nizam0786's avatar

It only works if I shorten the table name?

munazzil's avatar

According to the Mysql, character should be 64 or less than that.

1 like
nizam0786's avatar

@MUNAZZIL - For some reason it's just not letting me, I have had to shorten the table names to work around it until I find a fix.

Please or to participate in this conversation.