Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add field using alter table on the migration laravel?

I use laravel 5.3

My migration like this :

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('api_token')->nullable();
            $table->string('email',100)->unique();
            $table->string('password')->nullable();
            $table->string('avatar',100)->nullable();
            $table->string('full_name',100)->nullable();
            $table->date('birth_date')->nullable();
            $table->smallInteger('gender')->nullable();
            $table->timestamps();
            $table->softDeletes();
        });
    }
    public function down()
    {
        DB::statement('SET FOREIGN_KEY_CHECKS = 0');
        Schema::dropIfExists('users');
        DB::statement('SET FOREIGN_KEY_CHECKS = 1');
    }     
}

I want to add new field like this :

$table->string('mobile_number',20)->nullable();

But I don't want to add it on the schema. I want to use alter table

On my staging server and live server had set automatic migration

So if I use alter table, it will automatic migration. So on the table in database will automatic add mobile_number field if the code merge to development or master

If I add on the schema, it will not automatically migrate

How can I add the field using alter table?

like image 759
moses toh Avatar asked Dec 01 '22 11:12

moses toh


2 Answers

You can use the schema to update an existing table. Create a new migration using the artisan command then add something like

Schema::table('users', function (Blueprint $table) {
    $table->string('mobile_number',20)->nullable();
});

If you really wanted to do RAW sql you can do something like

DB::statement("ALTER TABLE users .....");

However the schema way is much better if you can get it to work

like image 110
Chris Phillips Avatar answered Dec 06 '22 08:12

Chris Phillips


In the command line, execute artisan command to add new migration for your table:

php artisan make:migration add_mobile_number_to_users_table --table=users

Then you can put your code inside the newly created migration file:

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->string('mobile_number',20)->nullable();
    }
}

public function down()
{
    Schema::table('users', function (Blueprint $table) {
        $table->dropColumn('mobile_number');
    }
}
like image 26
spirit Avatar answered Dec 06 '22 08:12

spirit