How to use PHP Enums with Laravel Eloquent models

Article author Jelle de Vries
Jelle de Vries
August 18, 2022 (Updated August 24, 2022)

In PHP 8.1 enums were introduced. They're great for defining "a closed set of possible values for a type" You can use them for values like languages, currencies, etc.

Something I found out recently is that you can use your PHP enums as value for your Laravel Eloquent model attributes.

You can achieve it by following these steps:

1. Define your enum

First, define your enum. Note that Eloquent models only support backed enums - a backed enum always has an integer or string as backed type. In the code below it's the status string.

enum ProductStatus: string
{
	case Publish = 'publish';
	case Private = 'private';
    case Unlisted = 'unlisted';
}

2. Add a '$casts' attribute to your Eloquent model

Next, add a $casts attribute to your Eloquent model. The value needs to be an array, with the key being your model's attribute, and the value a class reference to your enum.

Eloquent stores your backed enum's integer or string in the database and when retrieving it converts the integer or string back to your enum. Therefore, your model's attribute should be of the same type, in this case a string.

class Product extends Model
{
	protected $casts = [
		'status' => ProductStatus::class,
  	];
}

3. Use the enum in your code

Finally, use the enum when working with model objects, as alternative to using magic strings (bad practice), class constants, etc. It also eliminates the need for third party enum implementations.

$product = new Product();
$product->status = ProductStatus::Publish;
$product->save();

////////
  
if ($product->status === ProductStatus::Publish) {
	...
}

Comments