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?
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
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');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With