search

Home  >  Q&A  >  body text

Laravel search via pure (unsupported) enumeration

I'm trying to perform a search in the database via a pure enum field:

enum Enum1 {
    case Case1;
}

Model::query()->where('enum1', Enum1::Case1)->first()

and it doesn't work, causing the error Error Object of class Enum1 Could not be conversion to string.

When I search by supported enums it works:

enum Enum2: int {
    case Case1 = 1;
}

Model::query()->where('enum2', Enum2::Case1)->first()

In Model->casts, provide values ​​for Enum1 and Enum2.

I know, I can search via Enum1::Case1->name, but that's not what I'm looking for. If possible, I'd like to get the right actors in place. What's the easiest/correct way to handle this problem?

P粉773659687P粉773659687296 days ago435

reply all(1)I'll reply

  • P粉946437474

    P粉9464374742024-02-04 12:19:52

    I think your problem is that MySQL has no native support for Enum fields.

    Eloquent in the where clause also expects the second argument to be a string or other "common" data type.

    Maybe at some point Laravel eloquent will support Enums, but I don't think that's the case currently.

    I see nothing wrong with using the following:

    enum Enum2: int {
        case Case1 = 1;
    }

    This articlehere actually discusses how to access DB with Enums, so please read it.

    The purpose of enumeration is to make the code easier to read after all. Use the "separation of concerns" principle to make the code more readable. We used constants and other tricks before they came to PHP8

    reply
    0
  • Cancelreply