Enums in Laravel Explained: A Simple Guide for Beginners


Understanding Enums in Laravel
An enum (short for enumeration) is a special kind of class that lets you define a group of named constants. These constants are fixed values that don't change, and they’re commonly used to represent a predefined set of options or categories.
Enums help make your code more readable, organized, and maintainable, especially when compared to using plain strings or integers.
Enums were introduced in PHP 8.1, offering a cleaner and safer way to work with fixed sets of values.
Creating an Enum
To define an enum in PHP, use the enum keyword followed by the name of the enum and a list of cases. The example below illustrates a simple enum representing some popular cryptocurrencies
Laravel doesn’t have a built-in make: enum command out of the box, but an enum can be created using the generic make command or by defining it manually.
On Windows (Using Command Prompt)
Step 1: Open Command Prompt
Press Win + R, type cmd, and press Enter.
Step 2: Navigate to Your Project Folder
Use cd to go to your project folder, for example:
cd C:\Users\YourName\Projects\my-php-app
Step 3: Create the Enums Folder
Create the app\Enums directory:
mkdir app\Enums
Step 4: Create the Enum File
Create the file CryptoCurrency.php inside the app\Enums folder:
app\Enums\CryptoCurrency.php
Step 5: Open the File in Your Editor
Open the code editor and navigate to the newly created file to begin defining the enum.
On Mac (macOS) or Linux
Step 1: Open Terminal
You can find Terminal in Applications > Utilities > Terminal or press Cmd + Space and type Terminal.
Step 2: Navigate to Your Project Folder
Use the cd
Command to change directories to your project root. For example:
cd ~/Projects/my-php-app
Step 3: Create the Enums Folder
Run the following command to create the folder app/Enums (if it doesn’t exist):
mkdir -p app/Enums
The -p option creates parent directories as needed.
Step 4: Create the Enum File
Create a new file named CryptoCurrency.php inside the app/Enums folder:
touch app/Enums/CryptoCurrency.php
Step 5: Open the File in Your Editor
You can now open the file in your favorite code editor (like VS Code) and start writing your enum.
Enum Syntax
To define an enum, you use the enum keyword followed by the name and the list of cases. Let’s look at a simple enum that lists some popular cryptocurrencies.
enum CryptoCurrency: int
{
case BITCOIN = 1;
case ETHEREUM = 2;
case SOLANA = 3;
case CARDANO = 4;
case POLKADOT = 5;
}
Explanation
In the above example:
CryptoCurrency is the name of the enum.
Each case represents a different cryptocurrency..
The int after the enum name specifies the type of values the constants will have, in this case, integers.
Each constant is associated with a specific integer value. For instance, Bitcoin is assigned the value 1, and ETHEREUM is assigned the value 2.
Why Use Enums?
Enums are ideal for working with a fixed set of related values, such as a list of supported cryptocurrencies, user roles, or trade types. Instead of relying on database tables or hardcoding values throughout the codebase, enums provide a way to define these constants in a centralized, type-safe manner.
This brings structure, clarity, and safety to the code.
Example Use Case
Imagine you want to retrieve all users who have "Bitcoin" set as their favorite cryptocurrency:
User::where('favorite_crypto', CryptoCurrency::getIdByName('Bitcoin'))->get();
In this case, CryptoCurrency::getIdByName('Bitcoin') returns the value 1, as defined in your enum.This eliminates the need to use raw strings or magic numbers directly in the query, resulting in cleaner and more maintainable code.
Benefits of Using Enums
Improved Readability
Using descriptive enum names like CryptoCurrency::getIdByName('Bitcoin') instead of raw values like 1 helps make the code more self-explanatory.Type Safety
Enums restrict values to a predefined set, so PHP will throw an error if an invalid value is used. This prevents bugs caused by typos or unsupported inputs.Centralized Management
If you need to update or expand the list (e.g., renaming or reassigning values), you only have to change the enum definition. This eliminates the need to search through your entire codebase.Using enums reduces the chance of human error, improves maintainability, and makes your logic easier to follow, especially as your application grows in complexity.
Using Enums in Your Code
Imagine writing a query to fetch all users holding a specific cryptocurrency. Instead of using plain strings or integers:
User::where('favorite_crypto', CryptoCurrency::BITCOIN->value)->get();
This is much clearer and safer :
User::where('favorite_crypto', 1)->get();
It’s also possible to create a helper method to convert a name into its corresponding ID:
public static function getIdByName(string $name): ?int
{
return match(strtoupper($name)) {
'BITCOIN' => self::BITCOIN->value,
'ETHEREUM' => self::ETHEREUM->value,
'SOLANA' => self::SOLANA->value,
'CARDANO' => self::CARDANO->value,
'POLKADOT' => self::POLKADOT->value,
default => null,
};
}
Enums in Conditional Logic
Enums are also particularly useful in match expressions and conditional statements. For example:
phpCopyEditfunction getCryptoDescription(CryptoCurrency $crypto): string
{
return match($crypto) {
CryptoCurrency::BITCOIN => 'Bitcoin - The original and most well-known cryptocurrency.',
CryptoCurrency::ETHEREUM => 'Ethereum - Known for smart contracts and dApps.',
CryptoCurrency::SOLANA => 'Solana - High-speed blockchain with low fees.',
CryptoCurrency::CARDANO => 'Cardano - A research-driven blockchain platform.',
CryptoCurrency::POLKADOT => 'Polkadot - Enables interoperability between blockchains.',
};
}
This simplifies returning different responses based on the selected cryptocurrency.
Example with a Switch Statement
You can also use enums in a switch statement, which makes conditional logic cleaner and easier to maintain:
enum CryptoCurrency: int
{
case BITCOIN = 1;
case ETHEREUM = 2;
case LITECOIN = 3;
case DOGECOIN = 4;
}
function getCryptoDescription(CryptoCurrency $crypto): string
{
switch ($crypto) {
case CryptoCurrency::BITCOIN:
return 'Bitcoin is the first and most widely recognized cryptocurrency.';
case CryptoCurrency::ETHEREUM:
return 'Ethereum is a decentralized platform for smart contracts.';
case CryptoCurrency::LITECOIN:
return 'Litecoin is a peer-to-peer cryptocurrency inspired by Bitcoin.';
case CryptoCurrency::DOGECOIN:
return 'Dogecoin started as a meme but has a strong community following.';
default:
return 'Unknown cryptocurrency.';
}
}
// Usage example
echo getCryptoDescription(CryptoCurrency::ETHEREUM);
Summary
Enums in PHP offer a robust, type-safe alternative to using plain constants or database lookups when dealing with a fixed set of related values like cryptocurrencies, user roles, or status codes. They improve readability and make code more self-explanatory, enforce type safety, reducing bugs caused by invalid inputs, provide centralized control, making it easier to update value sets, and work seamlessly in conditionals and queries, removing the need for hardcoded strings or magic numbers
Using enums helps make PHP applications cleaner and easier to maintain as they scale.
References
1 . PHP Manual – Enumerations:
https://www.php.net/manual/en/language.enumerations.php
2 .PHP RFC: Enumerations (Official proposal introducing enums in PHP 8.1):
https://wiki.php.net/rfc/enumerations
3 .Stitcher.io – PHP Enums Explained:
https://stitcher.io/blog/php-enums
Subscribe to my newsletter
Read articles from Chidinma Okwuoha directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Chidinma Okwuoha
Chidinma Okwuoha
I am a frontend developer (vue.js)