Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

luddinus's avatar

Best way to transform INPUT data

Hi.

I'm using dingo/api which uses Fractal to transform OUTPUT data, very nice.

How do you transform the input data? I know we could use Mutators/Accesors or override the "input" method of the FormRequest I think.

Imagine I want to save a user which but the username always in lowercase. Today I would do a "setUsernameAttribute" method on the User model but I would like to do somethig like this:

// method controller
public function register(UserRegisterRequest $request, UserInputTransformer $inputTransformer)
{
    $data = $inputTransformer->transform($request->all());

    User::create($data);
}

// input transformer
class UserInputTransformer {
   public function transform($data)
   {
      return [
         'username' => strtolower($data['username']),
         // etc.
      ];
   }
}

What do you think?

0 likes
5 replies
mikemclin's avatar

One thing to mention, is that the Sanitizer package referenced only allows you to transform values in an array. So, if you want to remove, add or change the name of any array keys, then it has to be done outside of the package.

I'm assuming many people are looking to transform input from their API format (camel case) to their Eloquent model format (snake case). In that situation, this package offers very little help.

jekinney's avatar

I think what your doing is fine. Personally on certain forms for security reasons the name attribute on the form inputs doesn't match the db rows to the input needs to be properly mapped to the db. Basically by doing the same thing via a trait on the applicable models.

Called the functions transformAndCreate() and transformAndUpdate(). So you can call it on the controller User::transformAndCreate($request);

liuhaonan's avatar

I have been looking for a suitable package to transform input date format to responding DB row date format (due to security reason, same as @mikemclin mentioned) but didn't get one. it probably looks like a "fractal for input", any recommendation if there is any suitable package?

Please or to participate in this conversation.