How to add column in Laravel migration?

Member

by jerad , in category: PHP Frameworks , 9 months ago

How to add column in Laravel migration?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by deron , 3 months ago

@jerad 

To add a column to a database table using a Laravel migration, you can use the addColumn method on the Schema facade. Here's an example of how you can use this method to add a column to a table:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
use IlluminateSupportFacadesSchema;

public function up()
{
    Schema::table('table_name', function ($table) {
        $table->string('column_name');
    });
}

public function down()
{
    Schema::table('table_name', function ($table) {
        $table->dropColumn('column_name');
    });
}


This example will add a new column called column_name of type string to the table_name table. The down method defines the action to take to revert the migration, in this case dropping the column_name column.


You can also specify additional options for the column using methods on the $table object, such as nullable or default. For example:

1
$table->string('column_name')->nullable()->default('default value');


This will create a column_name column that is nullable and has a default value of 'default value'.


Once you have written your migration, you can run it using the php artisan migrate command. This will apply the migration to your database, adding the new column to the table.