Great questions! Let’s clarify how Laravel handles enum casting and how you should compare them.
1. Does Eloquent always return an enum instance for casted attributes?
Yes, if you use native PHP enums in your $casts array (as you did), Eloquent will always return an instance of the enum for that attribute when you access it from your model.
Example:
$booking = Booking::find(1);
var_dump($booking->third_party_status instanceof ThirdPartyStatus); // true
2. Which comparison is correct?
Given your enum cast, you should compare enum instances, not their values:
if ($booking->third_party_status === ThirdPartyStatus::CONFIRMED) {
// This is correct!
}
This works because both sides are instances of the same enum and the same case.
Do NOT compare the enum instance to its value directly:
if ($booking->third_party_status === ThirdPartyStatus::CONFIRMED->value) {
// This will always be false!
}
Here, you’re comparing an enum instance to an integer, which will never be equal.
3. When should I use ->value?
Use ->value when you need the raw value (e.g., for database queries, JSON output, or comparisons with non-enum data):
// Example: Querying by value
$confirmedBookings = Booking::where('third_party_status', ThirdPartyStatus::CONFIRMED->value)->get();
Or, if you want to output the value:
echo $booking->third_party_status->value; // outputs 1
Summary Table
| Use Case | Comparison Syntax |
|---|---|
| Comparing model attribute to enum case | $booking->third_party_status === ThirdPartyStatus::CONFIRMED |
| Comparing to raw value | $booking->third_party_status->value === 1 |
| Querying by value | ->where('third_party_status', ThirdPartyStatus::CONFIRMED->value) |
In short:
- Use enum cases for comparisons in PHP (
===with enum instances). - Use
->valuewhen you need the underlying value (e.g., for queries or output).
Let me know if you need more examples!