Does eloquent support array enum casting?

Viewed 1517

Eloquent allows Enum Casting.

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:

use App\Enums\ServerStatus;

/**
 * The attributes that should be cast.
 *
 * @var array
 */
protected $casts = [
    'status' => ServerStatus::class,
];

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:

if ($server->status == ServerStatus::provisioned) {
    $server->status = ServerStatus::ready;

    $server->save();
}

Is it possible to use enum casting in eloquent for array values?

I have an existing eloquent model that use to have one type. And now it needs to support multiple.

Does Laravel support array enum casting or ist this not possible? What would be an alternative approach to achieve something similar?

1 Answers

you can use spatie/laravel-enum

after installing it:

composer require spatie/laravel-enum

you can use it for array enum casting, something like:

protected $casts = [
    'status' => StatusEnum::class.':collection',
];

and if the status is nullable you can:

protected $casts = [
    'status' => StatusEnum::class.':collection,nullable',
];

this package also provider validation rule and other features.

and here is an interesting pull request that has been merged, but I did not test it.

Related