In this article, we'll see how to change column name and type in laravel 10 migration. Here, we'll learn about how to change existing column names or data types in laravel 10. To rename a column, you may use the renameColumn
method provided by the schema builder.
If you are running a database installation older than one of the following releases, you should ensure that you have installed the doctrine/dbal
library via the Composer package manager before renaming a column:
- MySQL <
8.0.3
- MariaDB <
10.5.2
- SQLite <
3.25.0
You can rename the column names using the renameColumn() function in laravel 10.
Schema::table('users', function (Blueprint $table) {
$table->renameColumn('from', 'to');
});
Now, we will install the doctrine/dbal package using the following composer command.
composer require doctrine/dbal
Example:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->text('description');
$table->boolean('is_publish')->default(0);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
Example:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class ChangePostsTableColumn extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$table->longText('description')->change();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
}
}
Example:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class ChangePostsTableColumn extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$table->renameColumn('title', 'name');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
}
}
You might also like:
- Read Also: How to Create AJAX Pagination in Laravel 10
- Read Also: Laravel 10 one to one Relationship Example
- Read Also: Laravel 10 many to many Relationship Example
- Read Also: How to Import Excel File into Database using Python