Skip to content

Commit eb2f7fa

Browse files
committed
document enum casting
1 parent d1674f0 commit eb2f7fa

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

eloquent-mutators.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
- [Attribute Casting](#attribute-casting)
88
- [Array & JSON Casting](#array-and-json-casting)
99
- [Date Casting](#date-casting)
10+
- [Enum Casting](#enum-casting)
1011
- [Encrypted Casting](#encrypted-casting)
1112
- [Query Time Casting](#query-time-casting)
1213
- [Custom Casts](#custom-casts)
@@ -326,6 +327,32 @@ By default, the `date` and `datetime` casts will serialize dates to a UTC ISO-86
326327

327328
If a custom format is applied to the `date` or `datetime` cast, such as `datetime:Y-m-d H:i:s`, the inner timezone of the Carbon instance will be used during date serialization. Typically, this will be the timezone specified in your application's `timezone` configuration option.
328329

330+
<a name="enum-casting"></a>
331+
### Enum Casting
332+
333+
> {note} Enum casting is only available for PHP 8.1+.
334+
335+
Eloquent also allows you to cast your attribute values to PHP enums. To accomplish this, you may specify the attribute and enum you wish to cast in your model's `$casts` property array:
336+
337+
use App\Enums\ServerStatus;
338+
339+
/**
340+
* The attributes that should be cast.
341+
*
342+
* @var array
343+
*/
344+
protected $casts = [
345+
'status' => ServerStatus::class,
346+
];
347+
348+
Once you have defined the cast on your model, the specified attribute will be automatically cast to and from an enum when you interact with the attribute:
349+
350+
if ($server->status == ServerStatus::provisioned) {
351+
$server->status = ServerStatus::ready;
352+
353+
$server->save();
354+
}
355+
329356
<a name="encrypted-casting"></a>
330357
### Encrypted Casting
331358

0 commit comments

Comments
 (0)