#Enum could not be converted to string

13 messages · Page 1 of 1 (latest)

past tinsel
#

Hi,
I have a little issue with my migration and enums.

According to the laravel documentations, I can define enum columns in the migration like this: $table->enum('column_name', Enum::cases()). But when I try to run it, it gives me this error:


  at vendor\laravel\framework\src\Illuminate\Database\Grammar.php:235
    231▕         if (is_array($value)) {
    232▕             return implode(', ', array_map([$this, __FUNCTION__], $value));
    233▕         }
    234▕
  ➜ 235▕         return "'$value'";
    236▕     }
    237▕
    238▕     /**
    239▕      * Escapes a value for safe SQL embedding.

  1   [internal]:0
      Illuminate\Database\Grammar::quoteString(Object(App\Enums\PeopleType))
  2   vendor\laravel\framework\src\Illuminate\Database\Grammar.php:232```

`app\Enums\PeopleTypes`:
```<?php

namespace App\Enums;

enum PeopleType: string
{
    case ACTOR = 'actor';
    case CREW = 'crew';
    case INFLUENCER = 'influencer';
    case OTHER = 'other';
}

The migration collumn in question:
$table->enum('type', PeopleType::cases())->default(PeopleType::OTHER);

I'm sorry if this is an amateur question. Thank you in advance for your help!

#

-# And I'm also sorry, if my grammar is bad

fallen lake
#

I think the issue is coming from ->default(PeopleType::OTHER), as there you'd probably need to use ->default(PeopleType::OTHER->value)
Also make sure you're up-to-date with the latest Laravel version, as things have been added/fixed for enums through minor releases

azure sedge
#

$table->enum('type', array_column(PeopleType::cases(), 'value')) ->default(PeopleType::OTHER->value);

#

The question is why would you use an enum column. Use a string and keep the enums dynamic for the future.

unkempt burrow
fallen lake
#

Wasn't going to mention that, but yes, enums are rather difficult to change later on 😅

past tinsel
#

I made it work like this: $table->enum('type', array_map(fn ($e) => $e->value, PeopleType::cases()))->default(PeopleType::OTHER);

fallen lake
past tinsel
#
  PHP Version ................................. 8.4.13```
fallen lake
#

The framework is currently at v12.37.0, so that's quite a lot of newer versions

past tinsel
#

So from now on I will use it like this: $table->string('type', 50)->default(PeopleType::OTHER->value);
Thanks for the help everyone!