For this scenario, imagine you have an existing "Article" model with a corresponding "create_articles_table" migration file and you want to rename the "url" and "synopsis" columns.
Before (Article Model)
- id
- url (column to be renamed)
- synopsis (column to be renamed)
- title
- content (previously not nullable)
- image
- created_at
After (Article Model)
- id
- title
- slug (newly updated column)
- summary (newly updated column)
- content (now can be nullable)
- image
- created_at
Step 1: Install Additional Dependency
In order to change/modify the column, you need an additional package dependency called "doctrine/dbal", run the composer command below to require it into the project.
composer require doctrine/dbal
Step 2: Create the Migration
To rename existing columns, you have to run the make migration command but instruct it to modify the existing table. Make use of the "--table=your-table-name" flag and specify the table that you want to modify the columns.
php artisan make:migration rename_url_synopsis_columns_of_articles_table --table=articles
$table->renameColumn('from', 'to');
$table->string('name')->nullable()->change();
Final Code
Once the migration class is created, define the necessary changes as follows.
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class RenameUrlSynopsisColumnsOfArticlesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('articles', function (Blueprint $table) { $table->renameColumn('url', 'slug'); $table->renameColumn('synopsis', 'summary'); $table->string('content')->nullable()->change(); }); } }
Fil Step: Run the Migration
Finally, run the migration command and the 2 columns name will now be renamed and the other column attribute will be updated.
php artisan migrate