To rename a column in a Laravel migration, you can use the renameColumn
method on the Blueprint
instance in your migration file.
Here’s an example of how you can use the renameColumn
method to rename a column called old_column
to new_column
in a table
:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class RenameColumnInTable extends Migration
{
public function up()
{
Schema::table('table', function (Blueprint $table) {
$table->renameColumn('old_column', 'new_column');
});
}
public function down()
{
Schema::table('table', function (Blueprint $table) {
$table->renameColumn('new_column', 'old_column');
});
}
}
You can then run the migration using the php artisan migrate
command.
Keep in mind that the renameColumn
method is not available on all database systems, so you may need to use a different method depending on your database server.
If you want to rename multiple columns at once, you can use the renameColumn
method multiple times within the same migration. For example:
class RenameColumnsInTable extends Migration
{
public function up()
{
Schema::table('table', function (Blueprint $table) {
$table->renameColumn('old_column_1', 'new_column_1');
$table->renameColumn('old_column_2', 'new_column_2');
$table->renameColumn('old_column_3', 'new_column_3');
});
}
public function down()
{
Schema::table('table', function (Blueprint $table) {
$table->renameColumn('new_column_1', 'old_column_1');
$table->renameColumn('new_column_2', 'old_column_2');
$table->renameColumn('new_column_3', 'old_column_3');
});
}
}
This will rename three columns in the table
: old_column_1
to new_column_1
, old_column_2
to new_column_2
, and old_column_3
to new_column_3
.