Adding Custom Char Type in Laravel Migration

So in one of my Laravel projects, I have to change a char type using migration. The task was adding nullable() to existing column.

After doing composer required doctrine/dbal to provide support changing column in migration, I created migration file using php artisan make:migration command that generates this file.

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddNullableToChar extends Migration
{
public function up()
{
Schema::table('the_table', function (Blueprint $table) {
$table->char('char_column_to_be_changed', 3)->nullable()->change();
});
}
public function down()
{
Schema::table('the_table', function (Blueprint $table) {
$table->char('char_column_to_be_changed', 3)->nullable(false)->change();
});
}
}

When I run php artisan migrate it will throw this error.

Doctrine\DBAL\DBALException: Unknown column type "char" requested. Any Doctrine type that you use has to be registered with \Doctrine\DBAL\Types\Type::addType(). You can get a list of all the known types with \Doctrine\DBAL\Types\Type::getTypesMap(). If this error occurs during database introspection then you might have forgotten to register all database types for a Doctrine Type. Use AbstractPlatform#registerDoctrineTypeMapping() or have your custom types implement Type#getMappedDatabaseTypes(). If the type name is empty you might have a problem with the cache or forgot some mapping information.

I found similar solution for the problem after reading this blog post that face an enum problem.

I created a custom Doctrine mapping type by extending existing StringType.

<?php
namespace App\Libraries\Doctrine;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\StringType;
class CharType extends StringType
{
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
return $platform->getVarcharTypeDeclarationSQL($fieldDeclaration, true);
}
public function getName()
{
return 'char';
}
}

It’s basically adding a true value into getVarTypeDeclarationSQL method that has char support.

On migration file, I registered this new type to make Doctrine know the char type.

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use App\Libraries\Doctrine\CharType;
use Doctrine\DBAL\Types\Type;
class AddNullableToChar extends Migration
{
public function __construct()
{
Type::addType('char', CharType::class);
}


public function up()
{
Schema::table('the_table', function (Blueprint $table) {
$table->char('char_column_to_be_changed', 3)->nullable()->change();
});
}
public function down()
{
Schema::table('the_table', function (Blueprint $table) {
$table->char('char_column_to_be_changed', 3)->nullable(false)->change();
});
}
}

This solution worked for me and php artisan migrate command run smoothly.