Laravel change column name or data type using migration Example; In this tutorial you will learn how to change name or datatype of exiting database table using creating new migration file. In previous article we already explain How to Rename Column Name in Laravel using Migration.
Below we have added step by step guide to how we can change the database table column or datatype in laravel or rename the name using new migration.
Previous Table Structure:
Here the table projects table migration where the ‘description’ datatype is text but we change it in ‘longtext’.
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProjectsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('projects');
}
}
Step 1: Install Doctrine For Change Datatype
In laravel changing the datatype we need to run the doctrine/dbal package in composer. So copy the below command and run in terminal.
composer require doctrine/dbal
Step 2: Create Migration
Now create a new migration just run the below command.
php artisan make:migration change_description_datatype_in_projects_table --table=projects
After running this command you have generated a new migration in database>migration directory. Open the file and add the below code in your up method.
public function up()
{
Schema::table('tasks', function (Blueprint $table) {
$table->longText('description')->change();
});
}
The down is important because when we lean the php artisan migrate:rollback command then the down method is running so here we change also in down method copy the below code and put in down method.
public function down()
{
Schema::table('tasks', function (Blueprint $table) {
$table->text('description')->change();
});
}
Read: How to Rename Column Name in Laravel using Migration
If you will see the database your column datatype it will be changed now. I hope this example help you.