Lesson 2: Using Enum on laravel

Enum is useful when you want to define value key pair that value is a number or low memory value and key is text that easy to remember. By the way, value will be stored to database to save memory and key will be used on source code to sugguest developer to remember what is it.
For example:
Video status Enum: display status of a video
Draft = 0
Public = 1
When a video is stored to database, the status is stored as 1 or 0 instead of draft/public that will save memory and increase query performance when query a video with status.
But Laravel do not have core library to support Enum so in order to implement Enum manually:
Create Enum parent class on /app/Http/Enums/Enum.php

<?php
namespace App\Http\Enums; 

abstract class Enum {
    public static function getAll() {
        $oClass = new \ReflectionClass(get_called_class());
        return $oClass->getConstants();
    }
    public static function getDisplay($value) {
        if (isset($value)){
            $oClass = new \ReflectionClass(get_called_class());
            $constants = $oClass->getConstants();
            foreach ($constants as $item) {
                if ($item['value'] == $value) return $item['display'];
            }
        }
        return false;
    }
	
	public static function getAllValue(){
		$all = self::getAll();
		
		return array_map ( function ($a) {
			return $a['value'];
		}, $all);
	}
}

Create video Enum file: /app/Http/Enums/VideoStatusEnum.php

<?php
namespace App\Http\Enums; 

class VideoStatusEnum extends Enum {
    const PUBLIC = ['value'=>1,'display'=>'Public'];
    const DRAFT = ['value'=>0,'display'=>'Draft'];
}

By the way when you want to display Video status to user when get from database, we use like

use App\Http\Enums\VideoStatusEnum;

$video = Video::create(['name' => 'Video 1', 'status' => VideoStatusEnum::DRAFT['value']]);
$video_status = VideoStatusEnum::getDisplay($video->status);
$draft_videos = Video::where('status' => VideoStatusEnum::DRAFT['value'])->all();

To validate by Laravel

class VideoController extends Controller
{
public function store(Request $request)
    {
        $validData = $request->validate([
            'title' => 'required',
            'description' => 'required',
            'path' => 'required|mimes:mp4|max:100000',
            'status' => 'required|in:' . implode(',', VideoStatusEnum::getAllValue())
            ]);
        //store logic
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *