Duvy
1 month ago

Camelcase HTTP parameters to snake_case Model properties converter

Posted 1 month ago by Duvy

In the Database columns and in the Model properties the default naming convention is snake_case, but if my frontend by default uses camelCase formatting sending HTTP Requests, is there any converter, or mapping possibility, I could do without manually doing it so for every request?

Example code:

In the Controller I use FormValidator validation with the name "RegisterUserValidator"

public function register(RegisterUserValidator $request)
{
    $this->userService->create($request);
}

The first inconvinience, that I need to specify for the "unique" what to check in the FormValidator class:

class RegisterUserValidator extends FormRequest
{

  public function rules()
  {
    return [
      'nickName' => 'required|unique:users,nick_name',
    ];
  }
}

After the validation I can replace the naming convention, I wasn't sure where this belongs to (Controller vs Service), but I placed it in the logic layer, so the "userService" looks like this:

public function create(Request $request)
{
    $attributes = $request->all();
    $attributes['nick_name'] = $attributes['nickName'];

/* End in the Repository layer I use Eloquent create() */
    User::create($attributes);
}

For the responses I use JsonResource, so only the incoming requests need some kind of magic.

Please sign in or create an account to participate in this conversation.