Today I was trying to create a string column for a slug in one of my tables. I required the column to have a unique index, but the table had information already, so, the moment the column was created, I got an error message informing me of duplicate and empty values in the new column.
public function up(){
Schema::table( 'states', function( Blueprint $table ){
$table->string( 'slug', 128 )->unique();
} );
}
Since the slug was going to contain the slugified version of the 'name' column, I decided to create the column in two steps. First the column was going to be a regular column and I was going to cycle through all the records creating the correct slug value using Str::slug(). After that I was going to modify the column to add the unique() option following Laravel's documentation:
public function up(){
Schema::table( 'states', function( Blueprint $table ){
$table->string( 'slug', 128 );
$states = State::all();
foreach( $states as $state ){
$state->slug = Str::slug( $state->name );
$state->save();
}
$table->string( 'slug', 128 )->unique()->change();
} );
}
I was thinking this was a fine solution, because I was not going to break any rules in my database since all the names were different. I ran the migration and I got a nice error:
SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'slug' (SQL: alter table `states` add `slug` varchar(128) not null)
Any ideas on how can I create correctly the migration?