8

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?

k0pernikus
  • 60,309
  • 67
  • 216
  • 347
  • As in cast each value of the array to a specific enum? – Rwd Nov 16 '21 at 17:39
  • @Rwd Basically yes. I want to have multiple values on a type property and that should translate to, most likely, a comma separated list of the enums in the database. I have the feeling I have to implement that myself. – k0pernikus Nov 16 '21 at 17:51

2 Answers2

4

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,
];
Elliot
  • 1,457
  • 13
  • 40
3

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.

OMR
  • 11,736
  • 5
  • 20
  • 35