How to Add an Extra Column in an Existing Table using Migration in Laravel?

07-Oct-2022

.

Admin

How to Add an Extra Column in an Existing Table using Migration in Laravel?

Hello Friends,

This tutorial will provide an example of how to add an extra column in an existing table using migration in laravel. it's a simple example of laravel migration add a column to a table. if you want to see an example of adding a column to table migration laravel then you are in the right place. This article goes into detail on laravel migration adds a column. Let's see bellow example laravel add a new column to existing table migration.

You can use this example with the versions of laravel 6, laravel 7, laravel 8, and laravel 9.

You have just to follow the below step and you will get the layout as below:

Step 1: Migration for main table:


In this step, we will create the migration for the title, body, and is_publish table. So let's run the below command to create tables.

php artisan make:migration CreatePostsTable

Next, simple update below code to migration file.

database/migrations/create_posts_table.php

<?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('body');

$table->boolean('is_publish')->default(0);

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('posts');

}

}

Step 2: Add Column using Migration:

Now, we will create the migration to add auther_id and note in a table. So let's run the below command to create tables.

php artisan make:migration ChangePostsTableColumn

Next, simple update below code to migration file.

database/migrations/change_posts_table_column.php

<?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->integer('auther_id');

$table->string('note');

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

}

}

I hope it can help you...

#Laravel