Access All Enum Cases In Laravel 10

Last updated 11th November, 2023

Introduction

When developing an application, I had the opportunity to leverage an Enum as the data source for a Laravel factory. This enabled me to manage and manipulate enumerated values within my project, specifically for the purpose of populating a factory seeder with a random value.

The Enum

I implemented a ServiceChargeType enum, which serves as a robust representation of the various charge types associated with payments. This enum simplifies the handling of payment categories, making it easier to work with them in a structured manner.

enum ServiceType: string
{
    case PURCHASE = 'purchase';
    case SUBSCRIPTION = 'subscription';
    case ON_DEMAND = 'on-demand';
}

The Cases Method

To access all the enumerated cases within an Enum, the cases method is employed. This method provides a clear and concise way to inspect the available cases and their respective properties.

ServiceType::cases()

// {name: "PURCHASE", value: "purchase"}

Extracting the Value

In the context of my factory, I required only the values associated with the Enum cases. To accomplish this, I used a Laravel's collections. This operation makes use of the Laravel pluck method to isolate and retrieve only the value property of each Enum case.

collect(ServiceType::cases())->pluck('value');

// "purchase", "subscription", "on-demand"

Hope this helped 🤙

No comments yet…

DevInTheWild.

Login To Add Comments.

Want More Like This?

Subscribe to occasional updates.

Related Articles