Enhance foreignIdFor() to Use the $table Property in Models for Table Name Resolution #53597
Unanswered
Waseem-Alhabash
asked this question in
Ideas
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Currently, the foreignIdFor() method in migrations infers the table name using the model's class name and Laravel's naming conventions. While this works in most cases, it can cause issues when the actual table name deviates from the naming convention. Developers must then explicitly pass the table name to the constrained() method, leading to repetitive code.
For example:
$table->foreignIdFor(App\Models\MealSection::class)->constrained('meal_section');
This adds unnecessary verbosity when the table name is already defined in the model's $table property.
Proposed Enhancement:
Modify the foreignIdFor() method to check if the $table property exists in the model. If it does, use its value for the constrained() method. If not, fallback to the current behavior of inferring the table name from the class name.
Proposed Behavior:
Use the $table property in the model to determine the table name:
protected $table = 'meal_section';
Allow for cleaner migrations:
$table->foreignIdFor(App\Models\MealSection::class)->constrained();
Retain existing behavior for models without a $table property.
Benefits:
Example Implementation:
This enhancement aligns migrations more closely with Eloquent's behavior, making Laravel more intuitive and developer-friendly.
Beta Was this translation helpful? Give feedback.
All reactions