paint-brush
Mapping Form Request to Eloquentby@deleu
7,226 reads
7,226 reads

Mapping Form Request to Eloquent

by Marco Aurélio DeleuApril 8th, 2018
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

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!

Company Mentioned

Mention Thumbnail
featured image - Mapping Form Request to Eloquent
Marco Aurélio Deleu HackerNoon profile picture

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!

1- The Test

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.

2- Transforming a Form Request into a Bag

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:

3- Wrapping up — The Handler

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.

4- Green tests!

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.