Schema::table('users', function (Blueprint $table) {
$table->dropTimestamps();
$table->dropColumn(['email', 'bio']);
$table->string('email', 20)->unique()->after('id');
$table->string('bio', 150)->after('surname');
$table->timestamps();
});
That is what I've got now. So, I have the columns existing atm in my table, but I want to modify and re-arrange them a bit. But when I run the migration, I get SQL error that email
column exists. And I will probably get the same error for the bio
and timestamps
as well. I kind of understand why this happens, so what am I asking is just for a workaround.
Is it possible to make what I want inside one single migration, or I have to create a migration for deleting the columns and then a separate migration for creating them the way I want?
Just break the schema up into two calls
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->dropTimestamps();
$table->dropColumn(['email', 'bio']);
});
Schema::table('users', function (Blueprint $table) {
$table->string('email', 20)->unique()->after('id');
$table->string('bio', 150)->after('surname');
$table->timestamps();
});
}
This way the change is occurring in one migration with two database calls.
Consider that if you drop the columns, you will lose ALL THE DATA contained therein. Normally this is a very bad and dangerous idea. If you instead need to simply change parameters, you should use the change()
function to make the required modifications to your schema. This will convert the existing data to the best of your databases's ability.
NEVER DROP COLUMNS on an in-use database unless you absolutely know what you're doing.
public function up()
{
Schema::table('users', function (Blueprint $table) {
// Add the unique constraint, for example
$table->string('email', 20)->unique()->after('id')->change();
// Add the length to the bio, for example
$table->string('bio', 150)->after('surname')->change();
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
// Remove length and constraints
$table->string('email')->unique(false)->change();
$table->string('bio')->change();
});
}
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