{"id":11441,"date":"2024-10-14T10:28:26","date_gmt":"2024-10-14T10:28:26","guid":{"rendered":"https:\/\/www.bacancytechnology.com\/qanda\/?p=11441"},"modified":"2025-06-04T08:12:34","modified_gmt":"2025-06-04T08:12:34","slug":"where-to-put-and-how-to-handle-enums-in-laravel","status":"publish","type":"post","link":"https:\/\/www.bacancytechnology.com\/qanda\/laravel\/where-to-put-and-how-to-handle-enums-in-laravel","title":{"rendered":"Where to Put &#038; How to Handle Enums in Laravel?"},"content":{"rendered":"<p>In Laravel, handling enums can be done in a few different ways depending on your use case. You can create enums as part of your PHP code (native PHP enums in PHP 8.1+) or use Laravel&#8217;s Enum packages like spatie\/laravel-enum. Here&#8217;s an overview of different ways to handle enums in Laravel:<\/p>\n<h2>1. Native PHP Enums (PHP 8.1+)<\/h2>\n<p>In PHP 8.1 and above, you can use native enums. Laravel supports these; you can use them within your models, database queries, and validation.<\/p>\n<h3>Creating a Native Enum:<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">namespace App\\Enums; \r\nenum UserType: string { \r\n          case ADMIN = 'admin'; \r\n          case EMPLOYEE = 'employee';\r\n}\r\n<\/pre>\n<h3>Using Enums in Models:<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">use App\\Enums\\UserType; \r\nclass User extends Model \r\n{\r\n          protected $casts = [\r\n                   'type' =&gt; UserType::class,\r\n           ];\r\n}\r\n<\/pre>\n<h3>Using Enums in Blade\/View:<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">@if($user-&gt;type === UserType::ADMIN)<\/pre>\n<p>This user is an admin.<\/p>\n<p>@endif<\/p>\n<h3>Using Enums in Validation:<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">use App\\Enums\\UserType;\r\n$validated = $request-&gt;validate([\r\n             'type' =&gt; ['required', Rule::in(UserType::cases())],\r\n ]);\r\n<\/pre>\n<h3>Converting Enum Values for API Responses:<\/h3>\n<p>You can easily convert enums to strings in JSON responses.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">public function toArray() { \r\n        return [ \r\n                   'type' =&gt; $this-&gt;type-&gt;value, \r\n        ]; \r\n}\r\n<\/pre>\n<h2>2. Custom Enum Classes (Pre-PHP 8.1)<\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">namespace App\\Enums;\r\nclass UserType {\r\n    const ADMIN = 'admin';\r\n    const EMPLOYEE = 'employee';\r\n\r\n    public static function values() {\r\n        return [\r\n            self::ADMIN,\r\n            self::EMPLOYEE,\r\n        ];\r\n    }\r\n}\r\n<\/pre>\n<h3>Using Custom Enums in Validation:<\/h3>\n<p>You can easily convert enums to strings in JSON responses.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">$validated = $request-&gt;validate([ \r\n                          'type' =&gt; [ 'required', Rule::in(UserType::values())], \r\n                    ]);\r\n<\/pre>\n<div class=\"qanda-read-box\"><div class=\"bg-light read-more-icon\"><img decoding=\"async\" src=\"https:\/\/assets.bacancytechnology.com\/qanda\/wp-content\/uploads\/2025\/04\/24061434\/read-txt.png\" alt=\"Also Read\"><p><\/p><h3>Also Read:<\/h3><a href=\"https:\/\/www.bacancytechnology.com\/blog\/laravel-cloud\" target=\"_blank\">Laravel Cloud<\/a><\/div><\/div>\n<p><strong>In Models:<\/strong> Manually casting using custom mutators or accessors is necessary.<\/p>\n<h2>3. Enum Packages (e.g., Spatie Enum)<\/h2>\n<p>If you need extra functionality like enum validation or database storage in Laravel, you can use a package like spatie\/laravel-enum.<\/p>\n<h3>Installation:<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">composer require spatie\/enum\r\n<\/pre>\n<h3>Creating an Enum Class Using Spatie:<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">namespace App\\Enums;\r\nuse Spatie\\Enum\\Enum;\r\nclass UserType extends Enum {}\r\n\r\n<\/pre>\n<h3>Using Spatie Enums:<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">$validated = $request-&gt;validate([\r\n    'type' =&gt; ['required', Rule::enum(UserType::class)],\r\n]);\r\n<\/pre>\n<p>Spatie&#8217;s package provides additional utilities for handling enums like advanced validation, transforming enums, etc.<\/p>\n<h2>4. Enums in Database<\/h2>\n<p>When working with enums in the database, you can use a VARCHAR or ENUM column type in your migrations.<\/p>\n<h3>Using an ENUM Column in Migrations:<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">Schema::table('users', function (Blueprint $table) {\r\n    $table-&gt;enum('type', ['admin', 'employee']);\r\n});\r\n<\/pre>\n<h3>Using Enums in Model Casts:<\/h3>\n<p>Combine it with native PHP enums or a custom casting class.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">protected $casts = [ 'type' =&gt; UserType::class, ];\r\n<\/pre>\n<h2>Conclusion<\/h2>\n<p><strong>Type Safety:<\/strong> If you&#8217;re using PHP 8.1+, prefer native enums for type safety and simplicity.<br \/>\n<strong>Database Compatibility:<\/strong> Use a <strong>VARCHAR<\/strong> column in your database instead of an <strong>ENUM<\/strong> column if you anticipate the possibility of adding new enum values in the future.<br \/>\n<strong>Validation:<\/strong> Always validate enum values to ensure valid data is being processed.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In Laravel, handling enums can be done in a few different ways depending on your use case. You can create enums as part of your PHP code (native PHP enums in PHP 8.1+) or use Laravel&#8217;s Enum packages like spatie\/laravel-enum. Here&#8217;s an overview of different ways to handle enums in Laravel: 1. Native PHP Enums [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":11442,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[10],"tags":[],"class_list":["post-11441","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-laravel"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/11441"}],"collection":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/comments?post=11441"}],"version-history":[{"count":12,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/11441\/revisions"}],"predecessor-version":[{"id":12497,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/11441\/revisions\/12497"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/media\/11442"}],"wp:attachment":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/media?parent=11441"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/categories?post=11441"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/tags?post=11441"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}