postgresqllaravellaravel-5laravel-migrations

Update enum column in Laravel migration using PostgreSQL


According to this answer, I have to run a raw query if I want to update an enum in MySQL. But with PostgreSQL, I can't use this query, and enum type for PostgreSQL in Laravel seems strange.

Is there any way to update enum in a migration for postgreSQL ?


Solution

  • Laravel use constraint on character varying for enum.

    Assuming there is a table mytable with an enum column status, we have to drop the constraint (named tablename_columnname_check) then add it in a migration like this:

    DB::transaction(function () {
        DB::statement('ALTER TABLE mytable DROP CONSTRAINT mytable_status_check;');
        DB::statement('ALTER TABLE mytable ADD CONSTRAINT mytable_status_check CHECK (status::TEXT = ANY (ARRAY[\'pending\'::CHARACTER VARYING, \'accepted\'::CHARACTER VARYING, \'canceled\'::CHARACTER VARYING]::TEXT[]))');
    });
    

    It solves the problem, hope it can help!