Cleaning Up Form Input with Transpose

Cleaning Up Form Input with Transpose

This post is adapted from my upcoming book, “Refactoring to Collections”. Learn more about the book and subscribe to updates here.

Dealing with arrays in form submissions is a pain in the ass.

Imagine you need to build a page that allows users to add multiple contacts at once. If a contact has a name, email, and occupation, ideally the incoming request would look something like this:

[ 'contacts' => [ [ 'name' => 'Jane', 'occupation' => 'Doctor', 'email' => 'jane@example.com', ], [ 'name' => 'Bob', 'occupation' => 'Plumber', 'email' => 'bob@example.com', ], [ 'name' => 'Mary', 'occupation' => 'Dentist', 'email' => 'mary@example.com', ], ], ];

The problem is that crafting a form that actually submits this format is surprisingly complicated.

If you haven’t had to do this before, you might think you can get away with something like this, using just a pinch of JavaScript to duplicate the form fields while keeping all of the field names the same:


Originally published at www.laravelfeed.com.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.