Reputation: 7810
I'm using Laravel migration files to help set up a MariaDB schema for my project. It works fine for the initial table setup of the schema, but after it has been created, how (if it's even possible at all) can I add one field to a migration file and have just that one field be created in the DB without affecting any of the existing fields/data?
As an example, let's say I have an up
method like the following:
public function up()
{
Schema::create('test_table', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
And then I want to add a desc
field as follows:
public function up()
{
Schema::create('test_table', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('desc')->nullable();
$table->timestamps();
});
}
If I run php artisan migrate
after adding the desc
field, will it work as intended, or will it mess up pre-existing stuff? I'm afraid to try without knowing what will happen, and I wanted to check first.
Also, I tried looking at the Laravel documentation for an answer to this question (https://laravel.com/docs/5.7/migrations), but couldn't find anything relevant.
Thanks.
Upvotes: 0
Views: 1005
Reputation: 4035
You should do this in terminal run command
php artisan make:migration add_desc_field_in_test_table --table=test_table
Then, in the up()
function in your migration
file, create the field:
public function up()
{
Schema::table('test_table', function (Blueprint $table) {
$table->string('desc')->nullable();
});
}
It will not mess the current table structure. It will just add the column desc
in test_table
.
Upvotes: 0
Reputation: 111839
Normally, you should create new migration where you just add new field. Method up
should look like this:
public function up()
{
Schema::table('test_table', function (Blueprint $table) {
$table->string('desc')->nullable()->after('name');
});
}
Notice that you don't use here Schema::create
but Schema::table
to update existing table.
Of course if you haven't deployed your app and can start from scratch you can modify existing migration, but assuming you are not sure, the best way is to create new migration where you only modify existing table.
Upvotes: 2