Skip to content

Instantly share code, notes, and snippets.

@MrPunyapal
Last active January 18, 2024 16:00
Show Gist options
  • Save MrPunyapal/7744c5ab8e4e85c740899f37c3a68b03 to your computer and use it in GitHub Desktop.
Save MrPunyapal/7744c5ab8e4e85c740899f37c3a68b03 to your computer and use it in GitHub Desktop.
Enhance Laravel Enums with Human-Friendly Labels using HasLabel Trait

HasLabel.php Trait

namespace App\Concerns\Enums;
 
trait HasLabel
{
    public function label(): string
    {
        return str($this->name)
        // convert to title case
        ->title()
        // replace underscores with spaces
        ->headline();
    }
}

Status.php Enum

namespace App\Enums;

use App\Concerns\Enums\HasLabel;

enum Status: int
{
    use HasLabel;

    case PENDING = 0;
    case FAILED = 1;
    case REFUNDED = 2;
    case PARTIALLY_REFUNDED = 3;
    case PARTIALLY_PAID = 4;
    case PAID = 5;
    case PARTIALLY_PAID_AND_REFUNDED = 6;
    case PARTIALLY_PAID_AND_PARTIALLY_REFUNDED = 7;
}

Examples

// some examples

use App\Enums\Status;

Status::PENDING->label(); 
// Pending
Status::FAILED->label(); 
// Failed
Status::REFUNDED->label(); 
// Refunded
Status::PARTIALLY_REFUNDED->label(); 
// Partially Refunded
Status::PARTIALLY_PAID->label(); 
// Partially Paid
Status::PAID->label(); 
// Paid
Status::PARTIALLY_PAID_AND_REFUNDED->label(); 
// Partially Paid And Refunded
Status::PARTIALLY_PAID_AND_PARTIALLY_REFUNDED->label(); 
// Partially Paid And Partially Refunded
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment