John Davidson

php - Laravel 9 altering table in migration does not add new column

0 comments
Message:


How do I alter an existing table in Laravel 9, while running tests on sqlite database?


I have a migration like so, which alters the default users table migration.


2022_07_27_151149_update_users_table.php


protected $tableName = 'users';

public function up()
{
Schema::table($this->tableName, function (Blueprint $table) {
$table->string('first_name', 75);
$table->string('last_name', 75);
$table->string('mobile', 12);
$table->dropColumn('name');
dump('in closure'); // <--- this does fire
});
dump('completed up'); // <--- this does fire
}

public function down()
{
Schema::table($this->tableName, function (Blueprint $table) {
$table->string('name');

if(Schema::hasColumn($this->tableName, 'first_name')){
$table->dropColumn('first_name'); // this also gets upset if I don't wrap it as above
}
if(Schema::hasColumn($this->tableName, 'last_name')){
$table->dropColumn('last_name');
}
if(Schema::hasColumn($this->tableName, 'mobile')){
$table->dropColumn('mobile');
}
});
}

I have altered the factory to take into account these changes.


public function definition()
{
return [
'first_name' => fake()->firstName(),
'last_name' => fake()->lastName(),
'mobile' => fake()->phoneNumber(),
'email' => fake()->safeEmail(),
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
}

But when used in any test I get exception PDOException: SQLSTATE[HY000]: General error: 1 table users has no column named first_name


abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
use DatabaseMigrations, RefreshDatabase;

/**
* @group debug
*/
public function testDebug(): void
{
$user = User::factory()->create(); // <--- error here
dd($user->toArray());
}
}

How do I alter an existing table with migrations in sqlite for testing?


Of note: I have implemented the fix here to get past the no transaction issue https://stackoverflow.com/a/71761089/2244284



My Answer:
tableName, function (Blueprint $table) {
$table->string('new_column')->nullable();
});
}

public function down()
{
Schema::table($this->tableName, function (Blueprint $table) {
$table->dropColumn('new_column');
});
}

Rate this post

3 of 5 based on 8542 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us