Laravel Tutorials

Request Handling with PHP Enums in Laravel

Published
Request Handling with PHP Enums in Laravel image

Laravel enhances its request handling capabilities with direct enum support, enabling type-safe processing of enumerated values from incoming requests. This feature simplifies input validation and ensures data consistency when working with predefined sets of values.

use App\Enums\UserRole;
// Basic enum retrieval
$role = $request->enum('role', UserRole::class);

Here's an example of building a subscription management system:

// app/Enums/SubscriptionTier.php
<?php

namespace App\Enums;

enum SubscriptionTier: string
{
    case FREE = 'free';
    case BASIC = 'basic';
    case PRO = 'pro';
    case ENTERPRISE = 'enterprise';

    public function getMonthlyLimit(): int
    {
        return match($this) {
            self::FREE => 1000,
            self::BASIC => 5000,
            self::PRO => 20000,
            self::ENTERPRISE => 100000
        };
    }
}

// app/Controllers/AccountController.php
namespace App\Http\Controllers;

use App\Enums\SubscriptionTier;
use App\Models\Account;
use Illuminate\Http\Request;

class AccountController extends Controller
{
    public function updateSubscription(Request $request, Account $account)
    {
        $newTier = $request->enum('tier', SubscriptionTier::class);
        if (!$newTier) {
            return response()->json([
                'error' => 'Invalid subscription tier provided'
            ], 422);
        }
        $account->update([
            'subscription_tier' => $newTier,
            'monthly_limit' => $newTier->getMonthlyLimit(),
            'upgraded_at' => now()
        ]);

        return response()->json([
            'message' => 'Subscription updated successfully',
            'account' => $account->fresh()
        ]);
    }
}

Example usage:

// Input request
{
    "tier": "pro"
}

// Success response
{
    "message": "Subscription updated successfully",
    "account": {
        "id": 1,
        "subscription_tier": "pro",
        "monthly_limit": 20000,
        "upgraded_at": "2024-02-01T10:30:00.000000Z"
    }
}

// Invalid input
{
    "tier": "premium"  // Non-existent enum value
}

// Error response
{
    "error": "Invalid subscription tier provided"
}

Request enum handling provides a robust way to process enumerated values while maintaining type safety and domain integrity.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Slow Job Alerts and Replica Commit IDs in Laravel 13.40 image

Slow Job Alerts and Replica Commit IDs in Laravel 13.40

Read article
Flock: A Free, Native Herd Alternative for Laravel image

Flock: A Free, Native Herd Alternative for Laravel

Read article
Live Props for Real-Time Updates in Inertia.js v3.11 image

Live Props for Real-Time Updates in Inertia.js v3.11

Read article
Cooldown Dependency Policy now in Composer 2.11 image

Cooldown Dependency Policy now in Composer 2.11

Read article
Email Sending and Testing for Laravel in One Account image

Email Sending and Testing for Laravel in One Account

Read article
Decide with Jev: Tie Every AI Check to the Exact Draft image

Decide with Jev: Tie Every AI Check to the Exact Draft

Read article