In this tutorial you will learn about the Laravel Change Table or Column Name with Data Type Tutorial and its application with practical example.
In this Laravel Change Table or Column Name with Data Type Tutorial I will show you how change column name or change column type with laravel migration. In this article I will also show you how to rename column name in laravel migration. You will also learn how to change data type in laravel migration. In this example we will be using “doctrine/dbal” composer package.
Laravel Change Table or Column Name with Data Type Tutorial
In this step by step tutorial I will demonstrate you how to change column name or how to change column data type in laravel migration.
Create Laravel Application
1 |
composer create-project laravel/laravel --prefer-dist laravel-example-app |
Create Model
1 |
php artisan make:model Student -m |
Add the table values for migration in migrations/timestamp_create_students_table file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateStudentsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('students', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('gender'); $table->string('email'); $table->string('dob'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('students'); } } |
Run laravel migration command:
1 |
php artisan migrate |
Install DBAL Package
In this step we will install doctrine/dbal composer package. Please use the following command to install doctrine/dbal package.
1 |
composer require doctrine/dbal |
Rename Laravel Column Name with Migration
In this example we will change column name “gender” to “subjects” so run command to create a new migration file:
1 |
php artisan make:migration rename_gender_in_students_table --table=students |
Add the code in newly created rename_gender_in_students_table.php file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class RenameGenderInStudentsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('students', function (Blueprint $table) { $table->renameColumn('gender', 'subjects'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('students', function (Blueprint $table) { $table->renameColumn('gender', 'subjects'); }); } } |
Run the below command to change or rename the column value gender to subjects: