0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

laravel-enum時代のasSelectArray()が懐かしいので、Traitで実装

Posted at

laravel-enum を使っていた頃を思い出す。

php8.1でlaravel10で archtechx/enums を使ってこねこねしている。

laravel-enum時代のasSelectArray()が懐かしいので、Traitで実装

<?php

namespace App\Enums\Trait;

trait SelectArray
{

    /**
     * @return array
     */
    public static function asSelectArray(): array
    {
        return collect(self::cases())
            ->mapWithKeys(fn ($enum) => [
                $enum->value => $enum->description(),
            ])
            ->all();
    }
}

Traitで作って
useして

<?php

namespace App\Enums;

use App\Enums\Trait\SelectArray;

enum DisplayEnum: string
{
    use SelectArray;

    case ENABLE = 'enable';
    case DISABLE = 'disable';

    /**
     * @return string
     */
    public function description(): string
    {
        return match ($this) {
            self::ENABLE => '表示',
            self::DISABLE => '非表示',
        };
    }
}

こんな感じで叩くと

DisplayEnum::asSelectArray();
[
    ['enable'] => '表示',
    ['disable'] => '非表示',
]

こんな感じで出てくるので後は自由に加工してくだされ。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?