Home > database >  Laravel 9 migrate: Object of class App\Enums\CaseSeverity could not be converted to string
Laravel 9 migrate: Object of class App\Enums\CaseSeverity could not be converted to string

Time:10-05

I have an Enum with string cases:

enum CaseStatus : string
{
    case Completed = 'completed';
    case Pending = 'pending';
    case Rejected = 'rejected';

    public function color(): string
    {
        return match($this)
        {
            self::Completed => 'badge-light-success',
            self::Pending => 'badge-light-warning',
            self::Rejected => 'badge-light-danger',
        };
    }
}

I am trying to migrate the table that uses this enum and set its default column value to CaseStatus::Pending

$table->string('status')->default(CaseStatus::Pending)->nullable();

When I migrate I get the error:

Object of class App\Enums\CaseSeverity could not be converted to string

CodePudding user response:

Eloquent model casts don‘t work in migration files because you’re not dealing with Eloquent models.

You need to instead use the underlying value of a backed enum in any migration commands:

$table->string('status')->default(CaseStatus::Pending->value)->nullable();

From https://www.php.net/manual/en/language.enumerations.backed.php

Backed Cases have an additional read-only property, value, which is the value specified in the definition.

<?php
print Suit::Clubs->value;
// Prints "C"
?>
  • Related