PHP Enum and examples in Laravel

Emeka Mbah
3 min readAug 6, 2022

Enum helps you to write more readable and maintainable code.

There are many reasons why you want to use enums:

  • DRY — You don’t want to repeat yourself. Having duplicated code is not easy to maintain. With enums, you have a single file to maintain for some related values.
  • Consistency — You want to ensure some values are the same through your code.
  • Leave the Database alone — Yeah, you don’t want to make costly queries to your database just to retrieve some static values

In these examples, I will show you how I use enum in Laravel/Vue

Enum helper trait for returning values


<?php
namespace App\Traits;
trait EnumValues
{
public static function values(): array
{
return array_column(self::cases(), 'value');
}
}

Enum helper trait for returning options

<?php
namespace App\Traits;
use Illuminate\Support\Str;
trait EnumOptions
{
public static function options(): array
{
$cases = static::cases();
$options = [];
foreach($cases as $case){
$label = $case->name;
if(Str::contains($label, '_')){
$label = Str::replace('_', ' ', $label);
}
$options[] = [
'value' => $case->value,
'label' => Str::title($label)
];
}
return $options;
}
}

An enum for related status

<?php
namespace App\Enums;
use App\Traits\{EnumOptions,EnumValues};
enum LoanRequestStatus: string
{
use EnumValues;
use EnumOptions;
case PENDING = 'pending';
case APPROVED = 'approved';
case PAID = 'paid';
case UNPAID = 'unpaid';
case REPAID = 'repaid';
case REJECTED = 'rejected';
case CLOSED = 'closed';
case ADJUSTED = 'adjusted';
case WORKFLOW = 'workflow';
case ON_HOLD = 'on-hold';
}

How I use enum in the migration file

<?phpuse Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use App\Enums\LoanRequestStatus;return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('loan_requests', function (Blueprint $table) {
$table->id();
$table->enum('status', LoanRequestStatus::values());
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('loan_requests');
}
};

Use as option

// in controller
return response([
'statuses' => LoanRequestStatus::options()
]);
// In vue
<select-input v-model="form.status" label="Status">
<option :value="null" />
<option v-for="status in statuses" :value="status.value">
{{status.label}}
</option>
</select-input>

Use in validation

<?phpnamespace App\Http\Requests\LoanRequest;use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use App\Enums\LoanRequestStatus;
class StoreLoanRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
return [
'status' => Rule::in(LoanRequestStatus::values())
];
}
}

Use in Model

<?phpnamespace App\Models;use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Casts\Attribute;
use App\Enums\LoanRequestStatus;
class LoanRequest extends Model
{
use HasFactory;
use SoftDeletes;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'status'
];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'is_pending' => 'boolean',
'status' => LoanRequestStatus::class
];
protected function isPending(): Attribute
{
return Attribute::make(
get: fn($value) => $this->status == LoanRequestStatus::PENDING
);
}
}

There you go! Start using enums where necessary :))
NB: This is currently supported in PHP 8.1
https://www.php.net/manual/en/language.enumerations.php

I’m also running the Latest Laravel version at the time of this writeup, which is Laravel 9.1

--

--

Emeka Mbah

I am a seasoned software developer who loves writing code in PHP, Laravel, and Javascript