Laravel Add New Column to Existing Table using Migration
Oct 07, 2022 . Admin
Hello Friends,
In this tutorial, I will show you that laravel adds a new column to an existing table using migration. let’s discuss laravel migration and add a column to a table. In this article, we will implement an add a-column to table migration laravel. In this article, we will implement a laravel migration and add a column to an existing table. Here, Creating a basic example of laravel migration adds a column.
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...