codewiser/laravel-enum-casting

将枚举类型转换为集合或数组

1.0.0 2022-06-06 11:19 UTC

This package is auto-updated.

Last update: 2024-09-07 15:02:41 UTC


README

PHP Composer

此包将枚举类型转换功能引入Laravel项目中。

安装

composer require codewiser/laravel-enum-casting

数据库

我们假设枚举类型存储在数据库中,格式为setjson对象。

集合

superuser,adminstrator

要从set数据类型转换枚举类型,使用set关键字。

JSON

["superuser","adminstrator"]

要从json数据类型转换枚举类型,使用jsonarray关键字。

用法

请参阅Laravel文档

AsArray

使用AsArray将枚举类型转换为简单的array。需要提供数据类型和枚举类作为参数。

use \Codewiser\Enum\Castable\AsArray;

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

AsArrayObject

使用AsArrayObject将枚举类型转换为ArrayObject。需要提供数据类型和枚举类作为参数。

use \Codewiser\Enum\Castable\AsArrayObject;

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

AsCollection

使用AsCollection将枚举类型转换为Collection。需要提供数据类型和枚举类作为参数。可选地,您还可以传递自定义集合类名称。

use \Codewiser\Enum\Castable\AsCollection;

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

参数顺序无关紧要。