Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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"
?>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading