Laravel Migration Change Datatype Text to Longtext Example

By Hardik Savani November 5, 2023 Category : Laravel

Hello Dev,

In this article, I will demonstrate an example of changing the text datatype to longtext in Laravel migration. I will explain the process in a simple manner, showing you how to update the datatype from text to longtext using Laravel migration.

Laravel migration provides way to add column name and datatype. But if you need to change column datatype then you have to install doctrine/dbal package to change datatype. In this example i will show you two ways to change datatype text to longtext in laravel migration.

In this example, i will change body column datatype text to textLong.

So, let's see the simple example of laravel migration change text to longtext.

Install doctrine/dbal: optional

First of all we need to install "doctrine/dbal" composer package. This package allow to use change() method to update datatype using laravel migration.

composer require doctrine/dbal

Default Created Table

Here, you will see the default created table screenshot.

Way 1: Create Migration

Create new migration using following command:

php artisan make:migration change_text_to_longtext_column

Now, You can update it as like the bellow:

database/migrations/migration_name.php

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

return new class extends Migration

{

/**

* Run the migrations.

*/

public function up(): void

{

Schema::table('posts', function (Blueprint $table) {

$table->longText('body')->change();

});

}

/**

* Reverse the migrations.

*/

public function down(): void

{

Schema::table('posts', function (Blueprint $table) {

});

}

};

Now, you are ready to run migration command:

php artisan migrate

You will see the layout as like the below:

Way 2: Create Migration

Create new migration using following command:

php artisan make:migration change_text_to_longtext_column

Now, You can update it as like the bellow:

database/migrations/migration_name.php

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

return new class extends Migration

{

/**

* Run the migrations.

*/

public function up(): void

{

\DB::statement('ALTER TABLE `posts` CHANGE `body` `body` LONGTEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL;');

}

/**

* Reverse the migrations.

*/

public function down(): void

{

Schema::table('posts', function (Blueprint $table) {

});

}

};

Now, you are ready to run migration command:

php artisan migrate

I hope it can help you...

Shares