1 month ago

Laravel 7 ForeignID() migrations

Posted 1 month ago by jcc5018

Hey, I have been working on getting my 170+ tables that I generated from my database set up correctly, but I am having difficulties with this foreignID functionality. I went through all my tables and replaced the FK's to $table->foreignId(foreign_id')->constrained(); as shown in the Laravel 7 documentation. My understanding is that this would replace the need for two lines of code like this. (Most all the previous inquiries I've found on the topic utilize this way and not the new way Laravel offers. )


But when I go run the migration:fresh option, i get errors on the first table with a Foreign key that says:

General error: 1824 Failed to open the referenced table 'users' (SQL: alter table ad_campaigns add constraint ad_campaigns_user_id_foreign foreign key (user_id) references users (id))

I'm going to assume this is because the users table hasnt been created yet. But I really thought the whole point of this foreignId() function was to make things easier. I've read in other places that perhaps foreign ids have to be created after everything else, but that implies that i would still need to add

$table->unsignedBigInteger('user_id'); in addition to the foreignId() or am I expected to create an entirely new set of migrations that adds all the respective foreign keys? Like I said, I have 170 tables, I really would prefer not to have to go through and edit everything again, or add another set of migrations just for something that i thought should be handled on initial creation.

I also need to know if on the pivot tables, after defining the relevant foreign keys, should you also be declaring them as combination primary keys? Thanks


Please sign in or create an account to participate in this conversation.