At some point, you may need to adjust specific columns in existing tables. Let's take a look at how to change existing columns in Laravel migrations.
All you really need is the change
method.
As an example, let's say you needed to increase the maximum length of a username
column in your users table. The original migration would have looked like this:
Schema::table('users', function (Blueprint $table) {
$table->string('username', 10);
});
To change this, simply create a new migration and use the change
method.
Schema::table('users', function (Blueprint $table) {
$table->string('username', 20)->change();
});
A really important aspect of modifying columns in migrations is that you need to include all the original modifiers you want to keep.
Sticking with the username
example, let's imagine the original migration specified that the username was unique, which makes sense:
Schema::table('users', function (Blueprint $table) {
$table->string('username', 10)->unique();
});
To change the length of the username and keep the unique modifier, we'd do this:
Schema::table('users', function (Blueprint $table) {
$table->string('username', 20)->unique()->change();
});
In short, copy the modifiers exactly, then make the change.
The change method doesn’t touch any indexes on the column. So, if you need to add or drop an index while updating the column, just do it explicitly using the index modifiers.
Here's an example straight from the Laravel docs:
// Add an index...
$table->bigIncrements('id')->primary()->change();
// Drop an index...
$table->char('postal_code', 10)->unique(false)->change();
If you ever need to rename a column, just use the renameColumn method from the schema builder. Simple as that.
Schema::table('users', function (Blueprint $table) {
$table->renameColumn('active', 'is_active');
});
Where active
is the current name of the column and is_active
is what you'd like to rename it to.