Schema Builder: changing table columns (only Laravel 5.0+)

While working with database migrations and schema builder, sometimes we do need to make changes to the columns that already exist. Can you do that and how?

For example, you want to change a type of column from VARCHAR(50) to VARCHAR(100). Within Migrations. I have a good and a bad news for you.

  • Good news: you can do that – with function change() (detailed below)
  • Bad news: it only appeared in Laravel 5.0 version, so you cannot use it in 4.2

How it works: when you create your migration file, just add a function change() at the end of your chain, related to the field:

public function up()
{
	Schema::table('users', function($table)
	{
	    $table->string('name', 50)->change();
	});
}

If you wonder, how to do that in Laravel 4.2 and prior versions, there’s also a way – you just run a raw statement:

public function up()
{
	Schema::table('users', function($table)
	{
	    DB::statement('ALTER TABLE users MODIFY COLUMN name VARCHAR(50)');
	});
}
Like our articles?
Check out our Laravel online courses!

4 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here