Hello developers! In this guide, we will see the laravel 10 add a column to an existing table. Here, we will learn about how to add a column to an existing table in laravel 10 migration. The table method on the Schema facade may be used to update existing tables.
In laravel add a new column to an existing table in a migration.
Like the create
method, the table
method accepts two arguments: the name of the table and a closure that receives an Illuminate\Database\Schema\Blueprint
instance you may use to add columns to the table
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
Schema::table('users', function (Blueprint $table) {
$table->integer('votes');
});
Create migration using the following command.
php artisan make:migration create_flights_table
Migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('flights', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('airline');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::drop('flights');
}
};
Add Column using Migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('flights', function (Blueprint $table) {
$table->string('passenger_name');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
$table->dropColumn('passenger_name');
}
};
Add Column After another column using Migration:
When using the MySQL database, the after
method may be used to add columns after an existing column in the schema.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('flights', function (Blueprint $table) {
$table->string('passenger_name')->after('airline');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
$table->dropColumn('passenger_name');
}
};
You might also like:
- Read Also: Laravel 10 Create Table Using Migration
- Read Also: Laravel 10 one to many Relationship Example
- Read Also: How to Sorting Column in Table in Laravel 10
- Read Also: How To Create Dynamic Line Chart In Laravel 10