Laravel search via pure (unsupported) enumeration
P粉773659687
P粉773659687 2024-02-03 20:19:05
0
1
366

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粉773659687
P粉773659687

reply all(1)
P粉946437474

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!