LARAVEL: How to rename a table column with migrations preserving data

Is it possible to alter your data structure without losing any data?

Gabriel Guerra
Mar 10 · 2 min read

Yes, you can! And it's pretty straightforward.

Credits and image licensing

As stated in Laravel manual:

To rename a column, you may use the renameColumn method on the Schema builder. Before renaming a column, be sure to add the doctrine/dbal dependency to your composer.json file:

Schema::table('users', function (Blueprint $table) {
$table->renameColumn('from', 'to');

You can do this following a few steps:

1) Check if you have the Doctrine DBAL library installed.
If you don’t know how to do this, just check at your composer.json file.
There should be a line like “doctrine/dbal”: “v2.4.2” (maybe in a different version), as shown in the code down below:

"require": {
"doctrine/dbal": "v2.4.2"

If the line it's absent, insert “doctrine/dbal”: “v2.4.2”, go to terminal and point it to your App directory.

Now, type "composer update" and wait for composer to finish all operations.

In the case you don't know, Composer is a dependency manager for PHP, used by Laravel.

2) Create a new migration typing in terminal:

php artisan make:migration alter_your_table --table=your_table

3) Now in your recent created migration you’ll insert:

Schema::table('users', function (Blueprint $table) {
$table->renameColumn('from', 'to');

We’re almost done! Now all you have to do is run your migrations like you always do:

php artisan migrate

That's it!

Happy coding :)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade