Before (Post Model)
- id
- title
- content
- image
- created_at
After (Post Model)
- id
- title
- slug (new column to be added)
- summary (new column to be added)
- content
- image
- created_at
Create the Migration
To add a new column you have to run the make migration command but instruct it as adding instead of creating a new migration. Make use of the "--table=your-table-name" flag and specify the table that you want to add new columns.
# for multiple columns like the scenario php artisan make:migration add_additional_columns_to_posts_table --table=posts # for single column you can explicitly mention it php artisan make:migration add_slug_to_posts_table --table=posts
Created Migration: 2021_06_14_210156_add_additional_columns_to_posts_table
Define the Columns
The command will create a new migration class called AddAdditionalColumnsToPostsTable and here define the columns to add to the migration in the "up" method. For the "down" method, drop the column as necessary and this will be called when the migration rollback command is executed.
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddAdditionalColumnsToPostsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('posts', function (Blueprint $table) { $table->string('slug')->unique(); $table->text('summary')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('posts', function (Blueprint $table) { $table->dropColumn(['slug', 'summary']); }); } }
Run the Migration
Finally, run the migration command and the 2 new columns will now be available in the table.
php artisan migrate