Adding column to existing table are easy as creating a new table and adding columns to it. In laravel migration we can add new colum to existing table using the same method we used in create migrations . Major difference between creating new table and updating new table is Schema::create
and Schema::table
In this tutorial we will create a new migration file and then will add a new column status
to the existing table .
I hope you know about How to make database connection in Laravel 8 ?
We will use the php
artisan command to generate the add column in laravel migration and php artisan migrate
command to modify the table.
I am assuming that you have already table movies
in database and now we are adding a new column.
Let’s understand the add column in laravel migration in laravel step by step
Step 1 : Generate migration file
To generate the migration file we will use the laravel artisan command so open the terminal in project and run below command
php artisan make:migration add_status_movies_table
Above command will create a migration file in folder database/migrations
Output: Created Migration: 2022_02_15_174050_add_status_movies_table
Step 2 : Open generated migration file and update
In the last step we created a migration file using the artisan command and now we wanted to add some more columns to schema of movies table.
so let’s open the file and start editing
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddStatusMoviesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
In the file there is a class named as AddStatusMoviesTable
and it extends Migration
class. AddStatusMoviesTable
contains two methods one is up and other one is down.
Up
is used to update the database scheme and down
method is used to rollback the changes of this migration. As you can see we are creating table movies
in up
method and dropping the table in down
method.
let’s add some more fields to our table before updating the database.
public function up()
{
Schema::table('movies', function (Blueprint $table) {
$table->integer("status");
});
}
public function down()
{
Schema::table('movies', function (Blueprint $table) {
$table->dropColumn("status");
});
}
Here we used Schema::table
to update the table.
Step 3 : Run Migration
In this step we will execute our migration in database using below command
php artisan migrate
This will create table in database and the output
Output: Migrating: 2022_02_15_174050_add_status_movies_table Migrated: 2022_02_15_174050_add_status_movies_table (20.08ms)
Screenshot Before:
Screenshot After:
Also Read : Laravel artisan command to generate controllers, Model, Components and Migrations