Laravel comes with API Resources to map an Eloquent object into a response. But what about the request? After struggling with this for a long time, I’m finally happy to introduce Bag!
In previous posts I’ve said how much of a TDD lover I am. I feel like it’s easier to discuss the problems of an implementation if I know how I’m going to be interacting with it. Let’s start with the test.
Simple create process, yet $administrator->create($request->validated())
would not work because a) we want to hash the password and b) the database column is called department_id
and not department
.
Form Requests are great classes for validating input data. After validating, we could use it to transform the input into something that Eloquent would understand. Here is a snippet for that.
Instead of using $request->validated()
from the Controller, we can now transform the request into a Data Bag by calling $request->toBag()
. The bag
will be responsible for doing all sorts of input transformation that we desire. Check it out:
As always, the Request Handler will type-hint the Form Request for Laravel to auto-validate the input data. If everything goes well, we can transform that data into a bag of validated data and pass it to Eloquent.
This implementation satisfy the test described in step 1. This finally satisfied my desire to keep a clean and intuitive API Request decoupled from the database structure in the same way that API Response can be transformed without requiring database changes.