Streamline Your Laravel API with Automatic Request Key Mapping
Er Amit Gupta

Er Amit Gupta @eramitgupta

About: Sr. Full Stack Developer - PHP, Laravel & Package Dev, Vue js, React js, Inertia js, Livewire, Alpine js, Javascript, jQuery, CSS Framework, VPS Server

Location:
Lucknow
Joined:
Sep 13, 2024

Streamline Your Laravel API with Automatic Request Key Mapping

Publish Date: Jul 23
0 0

Building modern web applications often means dealing with the naming convention mismatch between frontend and backend systems. Your React or Vue frontend might use camelCase (firstName, emailAddress), while your Laravel backend expects snake_case (first_name, email_address). This disconnect creates friction in development and requires manual transformation logic that clutters your codebase.

Enter the Laravel Case Mapper Request package—a elegant solution that automatically transforms incoming request keys to match your validation expectations using PHP 8+ attributes.

The Problem: Frontend-Backend Naming Convention Conflicts

Modern frontend frameworks like React and Vue.js typically follow camelCase naming conventions:

const userData = {
  firstName: "John",
  lastName: "Doe", 
  emailAddress: "john@example.com",
  phoneNumber: "123-456-7890"
}
Enter fullscreen mode Exit fullscreen mode

However, Laravel and PHP generally follow snake_case conventions:

$rules = [
  'first_name' => 'required|string',
  'last_name' => 'required|string', 
  'email_address' => 'required|email',
  'phone_number' => 'required|string'
];
Enter fullscreen mode Exit fullscreen mode

Traditionally, developers solve this by manually transforming keys in controllers or middleware, leading to repetitive code and potential inconsistencies across the application.

The Solution: Attribute-Based Request Mapping

The Laravel Case Mapper Request package introduces a clean, declarative approach using PHP 8+ attributes. Simply annotate your FormRequest classes with the desired mapping strategy, and the package handles the transformation automatically.

Key Features

  • Zero Configuration: No config files to publish or core modifications required
  • Attribute-Based Syntax: Clean, declarative mapping using #[MapName(...)]
  • Multiple Case Formats: Support for camelCase, snake_case, StudlyCase, and UPPERCASE
  • Seamless Integration: Works directly with Laravel FormRequest validation
  • Extensible: Create custom mappers for specialized transformation logic
  • Framework Agnostic: Compatible with any frontend framework (React, Vue, Angular, etc.)

Supported Case Transformations

The package includes four built-in mappers to handle common naming convention scenarios:

Mapper Class Input Format Output Format Use Case
SnakeCaseMapper firstName first_name Frontend camelCase → Backend snake_case
CamelCaseMapper first_name firstName Backend snake_case → Frontend camelCase
StudlyCaseMapper FirstName first_name PascalCase → snake_case
UpperCaseMapper FIRSTNAME firstname UPPERCASE → lowercase

Implementation Guide

Installation

Install the package via Composer:

composer require erag/laravel-case-mapper-request
Enter fullscreen mode Exit fullscreen mode

No additional configuration or publishing steps required—the package is ready to use immediately.

Step 1: Create a Form Request

Generate a new FormRequest using Laravel's artisan command:

php artisan make:request ContactRequest
Enter fullscreen mode Exit fullscreen mode

Step 2: Configure the Mapping

Add the required trait and attribute to your FormRequest class:

 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email_address' => 'required|email',
            'phone_number' => 'nullable|string'
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

The #[MapName(SnakeCaseMapper::class)] attribute tells the package to transform incoming camelCase keys to snake_case before validation.

Step 3: Use in Controller

Your controller remains clean and focused on business logic:

validated();

        $contact = Contact::create($validated);

        return response()->json([
            'message' => 'Contact created successfully!',
            'data' => $contact
        ], 201);
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Frontend Implementation

Your frontend can maintain its preferred naming convention. Here's a Vue.js example using Inertia:













      Submit Contact





import { useForm } from '@inertiajs/vue3'

const form = useForm({
  firstName: '',
  lastName: '',
  emailAddress: '',
  phoneNumber: ''
})

function submitForm() {
  form.post('/contacts')
}

Enter fullscreen mode Exit fullscreen mode

The Magic: Automatic Transformation

When the form is submitted, the package automatically transforms the request data:

Frontend sends:

{
  "firstName": "John",
  "lastName": "Doe", 
  "emailAddress": "john@example.com",
  "phoneNumber": "123-456-7890"
}
Enter fullscreen mode Exit fullscreen mode

Backend receives for validation:

[
  'first_name' => 'John',
  'last_name' => 'Doe',
  'email_address' => 'john@example.com', 
  'phone_number' => '123-456-7890'
]
Enter fullscreen mode Exit fullscreen mode

The transformation happens before validation, ensuring your validation rules work seamlessly with the expected key names.

Creating Custom Mappers

For specialized transformation requirements, you can create custom mappers by implementing the CaseMapperContract:

mapWithKeys(fn($value, $key) => [
                Str::kebab($key) => $value
            ])
            ->toArray();
    }
}
Enter fullscreen mode Exit fullscreen mode

Then apply it to any FormRequest:

#[MapName(KebabCaseMapper::class)]
class ProductRequest extends FormRequest
{
    use HasKeyTransformers;

    // Implementation...
}
Enter fullscreen mode Exit fullscreen mode

Advanced Use Cases

API Versioning

Different API versions might require different naming conventions:

// v1 API - snake_case
#[MapName(SnakeCaseMapper::class)]
class V1UserRequest extends FormRequest
{
    // ...
}

// v2 API - camelCase  
#[MapName(CamelCaseMapper::class)]
class V2UserRequest extends FormRequest
{
    // ...
}
Enter fullscreen mode Exit fullscreen mode

Multi-Platform Support

Support different client platforms with varying conventions:

// Mobile app requests (camelCase)
#[MapName(SnakeCaseMapper::class)]
class MobileUserRequest extends FormRequest
{
    // ...
}

// Legacy system integration (UPPERCASE)
#[MapName(UpperCaseMapper::class)]  
class LegacyUserRequest extends FormRequest
{
    // ...
}
Enter fullscreen mode Exit fullscreen mode

Performance Considerations

The package performs key transformation during the request lifecycle, specifically before validation. The overhead is minimal since it's a simple array key mapping operation using Laravel's efficient Collection methods.

For high-traffic applications, the transformation cost is negligible compared to database operations and other request processing overhead.

Benefits for Development Teams

Consistency Across Projects

Standardize how different naming conventions are handled across your Laravel applications.

Reduced Boilerplate Code

Eliminate repetitive key transformation logic in controllers and services.

Better Developer Experience

Frontend developers can use their preferred naming conventions without backend constraints.

Maintainable Codebase

Centralized transformation logic makes updates and changes easier to manage.

Type Safety

Works seamlessly with Laravel's validation system and IDE autocompletion.

Best Practices

Choose the Right Mapper

Select mappers based on your primary frontend framework:

  • React/Vue.js: Use SnakeCaseMapper to convert camelCase to snake_case
  • Legacy systems: Use UpperCaseMapper for UPPERCASE transformations
  • Mixed environments: Create custom mappers for specific transformation rules

Consistent Application

Apply the same mapping strategy across related FormRequests to maintain consistency in your API.

Documentation

Document your chosen naming conventions in API documentation to help frontend developers understand the expected formats.

Conclusion

The Laravel Case Mapper Request package solves a common pain point in modern web development by providing a clean, attribute-based solution for handling naming convention mismatches between frontend and backend systems.

By eliminating the need for manual key transformation and providing a declarative syntax, it helps teams maintain cleaner codebases while supporting flexible naming conventions across different platforms and frameworks.

Whether you're building a new Laravel API or refactoring an existing one, this package offers a zero-configuration solution that integrates seamlessly with Laravel's existing FormRequest validation system.

Comments 0 total

    Add comment