-1

I have a php8 enum type

enum OperationTypes: string
{
    case PointsAdd = 'points-add';
}

I need to be sure how to properly use it in Laravel database querybuilder. For example:

Model::where('type', OperationTypes::PointsAdd)
or 
Model::where('type', OperationTypes::PointAdd->value)

Model::whereIn('type', [OperationTypes::PointAdd])
or
Model::whereIn('type', [OperationTypes::PointAdd->value])

What is correct way?

3
  • Did you test it out? Did you receive any errors? Commented Mar 21, 2024 at 10:31
  • Anything not working with these snippets? Commented Mar 21, 2024 at 10:31
  • Unless you dont explicitly define casts, you should put in the 2nd argument whatever is written in the database for column type? Commented Mar 21, 2024 at 10:46

1 Answer 1

0

Model::where('type', OperationTypes::PointsAdd) passes an object of type OperationTypes to the where clause, which is not going to work.

Model::where('type', OperationTypes::PointAdd->value) passes a string to the where clause, and is the correct way to use enums in queries.

It would be nice if PHP enums supported the toString magic method to automatically cast themselves, but unfortunately they don't.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.