Hello Artisan,
In this Laravel migration change column name and type tutorial, you will learn how to change column name in laravel migration without losing data. You know sometimes we need to change column type or column name in Laravel.
But it is best practice to change it without losing data and of course avoiding manual processes with migration. So i am here to show you the process of changing column name and type in laravel migration without losing data.
This article is on laravel migration change column name. I will use doctrine/dbal
composer package to do it. Let's see an example of changing column name and type example laravel migration.
First of all, we need to install the "doctrine/dbal"
composer package.
composer require doctrine/dbal
Now assume we have a table schema like that.
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('body');
$table->boolean('is_publish')->default(0);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
Now we would like to change the body type text
to longText
. How we can do that?
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('body')->change();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
}
}
Now we would like to rename the title
to name.
How we can do that?
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()
{
}
}
Read also: Laravel Suspicious Logins Attempt Detector Example
Hope it can help you.
#laravel #laravel-8x #laravel-migration