Simplified Enum Handling with Default Values in Laravel

Laravel simplifies enum retrieval from requests with an enhanced enum() method that supports default values, making your code cleaner and more expressive.
When working with enums in request data, you often need to provide fallback values when the enum parameter is missing or invalid. The enhanced enum() method now accepts a third parameter for default values, eliminating the need for additional null coalescing logic.
Let's see how it works:
// Before
$chartType = request()->enum('chart_type', ChartTypeEnum::class) ?: ChartTypeEnum::Bar;
// After
$chartType = request()->enum('chart_type', ChartTypeEnum::class, ChartTypeEnum::Bar);
Real-World Example
Here's how you might use this in a dashboard controller:
class DashboardController extends Controller
{
public function analytics(Request $request)
{
$params = [
'chart_type' => $request->enum('chart_type', ChartType::class, ChartType::Line),
'period' => $request->enum('period', ReportPeriod::class, ReportPeriod::Monthly),
'status' => $request->enum('status', OrderStatus::class, OrderStatus::All),
'sort_by' => $request->enum('sort_by', SortOption::class, SortOption::CreatedAt)
];
return $this->generateReport($params);
}
public function userPreferences(Request $request)
{
$preferences = [
'theme' => $request->enum('theme', Theme::class, Theme::Light),
'language' => $request->enum('language', Language::class, Language::English),
'timezone' => $request->enum('timezone', Timezone::class, Timezone::UTC),
'notification_frequency' => $request->enum(
'notification_frequency',
NotificationFrequency::class,
NotificationFrequency::Daily
)
];
$request->user()->updatePreferences($preferences);
}
}
This enhancement makes your enum handling more concise and readable, especially when dealing with multiple enum parameters that need sensible defaults.
Stay Updated with More Laravel Tips
Enjoyed this article? There's plenty more where that came from! Subscribe to our channels to stay updated with the latest Laravel tips, tricks, and best practices:
- Follow us on Twitter @harrisrafto
- Join us on Bluesky @harrisrafto.eu
- Subscribe to our YouTube channel harrisrafto