@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.
@jerad
To add a column in Laravel migration, you need to follow these steps:
Step 1: Open the terminal and run the following command to create a new migration file:
1
|
php artisan make:migration add_column_name_to_table_name --table=table_name |
Replace add_column_name_to_table_name
with a suitable name for your migration file and replace table_name
with the name of the table in which you want to add the column.
Step 2: Open the created migration file (located in the database/migrations
directory) and add the new column using the addColumn
method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
use IlluminateDatabaseMigrationsMigration; use IlluminateDatabaseSchemaBlueprint; use IlluminateSupportFacadesSchema; class AddColumnNameToTableName extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('table_name', function (Blueprint $table) { $table->string('column_name')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('table_name', function (Blueprint $table) { $table->dropColumn('column_name'); }); } } |
Replace column_name
with the name of the new column you want to add.
Step 3: Save the migration file and run the migration command:
1
|
php artisan migrate |
This will run all pending migrations, including the new one which adds the column to the specified table.
After running the migration, the new column will be added to the table specified in the migration file.