DEV Community

Cover image for How to Change Table Name using Laravel Migration?
Denis Sinyukov
Denis Sinyukov

Posted on • Updated on • Originally published at coderden.dev

How to Change Table Name using Laravel Migration?

In this guide, you will learn how to change the table name when migrating laravel.

In some cases you need to change the table name, the reasons may be different. One such change is to extend the logic of a table. Previously, a table served only certain purposes, but over time it will be used for more.

In this tutorial we will take the polymorphic table job_quality_controls , which served as a quality control (QC) layer in the business logic, for different kinds of job (entity in the project logic). Within each job, different modules are used, such as orders, estimates, etc.

Structure of the table

INT entity_id
STRING entity_type
INT user_id
Enter fullscreen mode Exit fullscreen mode

Over time, some modules began to expand and the need to add QC for the orders module. Having a ready table we used it. But it has the wrong name. Because it previously contained other entities.

Rename table using migration

Thanks to migration we can change the table and not confuse developers with incorrect table names.

public function up()
{
    Schema::rename('job_quality_controls', 'quality_control_entities');
}
Enter fullscreen mode Exit fullscreen mode

If you have indexes in the table, they will have the old name. To fix this you need to delete and recreate the index.

Useful Commands

$table->renameIndex('from', 'to');
$table->dropIndex(['user_id']);
$table->dropForeign(['user_id']);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)