Laravel Tutorials

Converting Array Values to Enum Instances with Laravel's mapInto Method

Published
Converting Array Values to Enum Instances with Laravel's mapInto Method image

Working with enums in Laravel becomes effortless with the enhanced Collection::mapInto method that now provides first-class support for PHP Enums, streamlining the conversion of array values into proper enum instances.

PHP 8.1's introduction of native Enums revolutionized how developers define type-safe sets of values. Laravel embraces this feature fully, and the Collection::mapInto method now offers an elegant way to transform raw data into strongly-typed enum instances - particularly valuable when processing user input that requires conversion to enum cases.

Here's the method in action:

public function store(Request $request)
{
$request->validate([
'statuses' => ['array'],
'statuses.*' => [new Enum(OrderStatus::class)],
]);
 
$statuses = $request
->collect('statuses')
->mapInto(OrderStatus::class);
 
if ($statuses->contains(OrderStatus::Urgent)) {
// Prioritize urgent orders
}
}

This approach becomes particularly powerful in complex business logic scenarios:

<?php
 
namespace App\Enums;
 
enum Permission: string
{
case ViewDashboard = 'view_dashboard';
case ManageUsers = 'manage_users';
case EditContent = 'edit_content';
case AccessReports = 'access_reports';
 
public function isAdminLevel(): bool
{
return in_array($this, [
self::ManageUsers,
self::AccessReports
]);
}
}
 
class RolePermissionsController extends Controller
{
public function assign(Request $request)
{
$request->validate([
'permissions' => ['array'],
'permissions.*' => [new Enum(Permission::class)],
]);
 
// Convert strings to Permission enum instances
$permissions = $request
->collect('permissions')
->mapInto(Permission::class);
 
// Verify admin-level permissions
$requiresAdminPrivileges = $permissions
->filter(fn (Permission $permission) => $permission->isAdminLevel())
->isNotEmpty();
 
if ($requiresAdminPrivileges && !$request->user()->isAdmin()) {
return back()->withErrors([
'permissions' => 'Admin privileges required for selected permissions'
]);
}
 
// Assign permissions to role
$request->role()->permissions()->sync(
$permissions->map->value->toArray()
);
 
return redirect()->route('roles.show', $request->role)
->with('message', 'Permissions updated successfully');
}
}

The mapInto method internally instantiates each enum by passing the original value to the enum class constructor. For string-backed enums, this seamlessly converts raw strings like 'view_dashboard' into the appropriate enum case Permission::ViewDashboard, providing type safety and enabling powerful enum methods throughout your application logic.

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 →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article