Last active
February 22, 2017 05:41
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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