Automatic/Implicit Index Creation for Foreign Keys (PostgreSQL and SQLite) #54343
Replies: 3 comments
-
I can confirm I am experiencing this exact same issue on Laravel 12.x with PostgreSQL 17.x. Following a similar schema structure (permissions table with foreign keys to roles and features, and a composite unique(['role_id', 'name'])), the index for the second foreign key (feature_id) is also not being created. A direct query against pg_indexes confirms the index is missing. Adding $table->index('feature_id'); explicitly solves the problem. This definitely seems like an unexpected behavior with the schema builder's optimization logic. |
Beta Was this translation helpful? Give feedback.
-
Further investigation led me to PR #49392, which seems to address this exact bug and was merged in Laravel 10.41.0. However, I am still experiencing this issue on a clean install of Laravel 12.x with PostgreSQL, which suggests there might be a regression or a different edge case that the original fix didn't cover. This seems to confirm the schema builder's index optimization logic is still not behaving as expected in all scenarios. |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Background
In MySQL, foreign key columns automatically receive corresponding indexes. However, PostgreSQL requires explicit index creation for foreign key columns. While this behavior is inherent to PostgreSQL and not related to Laravel, we can enhance Laravel's handling of this database-specific difference.
Despite our Schema DDL abstraction layer, migrations can produce different database structures when run on MySQL versus PostgreSQL/SQLite due to how each database handles index creation for foreign keys.
Proposed Solution
Add a configuration option in Laravel to automatically create indexes for PostgreSQL foreign key columns, making the behavior consistent with other supported databases.
Configuration
Current Usage
Desired Usage
Implementation Considerations
A mechanism should be provided to override the automatic index creation when needed
References
MySQL
https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html
SQLite
https://www.sqlite.org/foreignkeys.html
PostgreSQL
https://www.postgresql.org/docs/current/indexes-unique.html
https://www.postgresql.org/docs/current/ddl-constraints.html
Beta Was this translation helpful? Give feedback.
All reactions