Skip to content

Instantly share code, notes, and snippets.

@paulofreitas
Last active February 22, 2017 05:41
Show Gist options
  • Save paulofreitas/6a3634a77782008fe3b78927d53792d4 to your computer and use it in GitHub Desktop.
Save paulofreitas/6a3634a77782008fe3b78927d53792d4 to your computer and use it in GitHub Desktop.
Laravel collection macro to transpose form data extracted from Refactoring to Collections book
<?php
/* Transpose Macro */
Collection::macro('transpose', function () {
$items = array_map(function (...$items) {
return $items;
}, ...$this->values());
return new static($items);
});
/ * Usage Example */
class ContactController
{
/* ... */
public function store (Request $request) {
collect($request->only('names', 'emails', 'occupations'))
->transpose()
->map(function ($contactData) {
return new Contact([
'name' => $contactData[0],
'email' => $contactData[1],
'occupation' => $contactData[2],
]);
})
->each(function ($contact) {
Auth::user()->contacts()->save($contact);
});
return redirect()->home();
}
/* ... */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment