k0pernikus
k0pernikus

Reputation: 66599

Does eloquent support array enum casting?

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?

Upvotes: 9

Views: 6560

Answers (2)

Elliot
Elliot

Reputation: 1616

As of Laravel v9+, it is now possible to cast arrays of enums.

use App\Enums\ServerStatus;
use App\Enums\ServerType;
use Illuminate\Database\Eloquent\Casts\AsEnumCollection;
use Illuminate\Database\Eloquent\Casts\AsEnumArrayObject;
 
/**
 * The attributes that should be cast.
 *
 * @var array
 */
protected $casts = [
    'statuses' => AsEnumCollection::class.':'.ServerStatus::class,
    'types' => AsEnumArrayObject::class.':'.ServerType::class,
];

Upvotes: 9

OMR
OMR

Reputation: 12208

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.

Upvotes: 3

Related Questions