Skip to content

Instantly share code, notes, and snippets.

@coderabbi
Last active January 7, 2017 08:11
Show Gist options
  • Save coderabbi/79b9879b123f450521248886466f6a00 to your computer and use it in GitHub Desktop.
Save coderabbi/79b9879b123f450521248886466f6a00 to your computer and use it in GitHub Desktop.
processModelsMappedFromFormRequest()
Collection::macro('transpose', function () {
$items = array_map(function (...$items) {
return $items;
}, ...$this->values());
return new static($items);
});
public function store(Request $request)
{
` $map = [
'names' => 'name',
'emails' => 'email',
'occupations' => 'occupation'
];
$this->processModelsMappedFromFormRequest(Contact::class, $map, $request, function($contact) {
Auth::user()->contacts()->save($contact);
});
return redirect()->home();
}
private function processModelsMappedFromFormRequest($model, $map, $request, $process)
{
collect($request->only(array_keys($map)))
->transpose()
->map(function ($data) use ($map) {
return new $model(array_combine(array_values($map), $data)));
})
->each($process);
}
// processModelsMappedFromFormRequest() was done quickly over morning coffee, may be unintentional psuedocode...
// Later... dawned on me that return new $model(array_combine(array_values($map), $data) limits it to 'create'
// rather than 'process'; perhaps updateOrCreate() instead of new, passing in an optional array of ids? That
// will have to wait for tomorrow's coffee, though...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment