Safely Change Column Types in Laravel with Migrations


- How to Change Column Types with Laravel Migrations
- Step 1: (Optional) Install the doctrine/dbal Package
- Step 2: Create a New Migration
- Step 3: Modify the Column
- Step 4: Run the Migration
- Summary
How to Change Column Types with Laravel Migrations
Sometimes, you need to change a column’s data type in your database. For example, maybe you want to change a column from string
to integer
, or from text
to boolean
. Laravel makes this possible using migrations.
In this post, we’ll walk you through the steps.
doctrine/dbal
Package
Step 1: (Optional) Install the Starting from Laravel 10, you no longer need to install the doctrine/dbal
package for most column modifications. However, if your application is running Laravel 10 and SQLite database, you still need to install it to enable column changes.
Run this command if you're on SQLite:
composer require doctrine/dbal
Step 2: Create a New Migration
Use the Artisan command to create a new migration file:
php artisan make:migration change_column_type_in_users_table
This will create a file in the database/migrations
folder.
Step 3: Modify the Column
Open the new migration file. Inside the up()
method, use the change()
method on the column. In this example, we are changing the age
column from string
to integer
:
use Illuminate\Support\Facades\Schema;use Illuminate\Database\Schema\Blueprint;use Illuminate\Database\Migrations\Migration; return new class extends Migration { public function up(): void { Schema::table('users', function (Blueprint $table) { $table->integer('age')->change(); }); } public function down(): void { Schema::table('users', function (Blueprint $table) { $table->string('age')->change(); }); }};
Important Considerations
- ✅ Ensure the column exists: Make sure the column name is correct and already exists in your table.
- ⚠️ Check data compatibility: Make sure the existing data in the column can be safely converted to the new type. Otherwise, the database will throw errors.
- 🔔 Re-define all modifiers: Since Laravel 10, when modifying a column, you must explicitly include all column modifiers you want to keep (like
nullable()
,default()
, orunsigned()
). Missing modifiers will be dropped.
Step 4: Run the Migration
Now apply the migration:
php artisan migrate
Summary
- Install
doctrine/dbal
only if needed (e.g. Laravel 9 and earlier versions or for SQLite in Laravel 10) - Create a migration
- Use
$table->type('column')->change()
- Be careful to re-include modifiers like
nullable()
- Run
php artisan migrate
This is how you update column types safely in Laravel.
Stay Updated.
I'll you email you as soon as new, fresh content is published.
Latest Posts