How can I add field using alter table on the migration laravel?
Solution 1
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
Solution 2
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');
}
}
Success Man
Updated on June 04, 2022Comments
-
Success Man almost 2 years
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?
-
moses toh over 6 yearsHow can do it if use alter table? Maybe you can update your answer. So there exist 2 choices
-
Chris Phillips over 6 years@SuccessMan Updated to add a RAW way of doing it, but the schema way should suit your needs
-
moses toh over 6 yearsOkay. Thanks for your help