Created
June 7, 2016 16:08
-
-
Save ohnotnow/20ae961fa8e2fc6c3d2cb12288be5684 to your computer and use it in GitHub Desktop.
Trying to build an array for laravel sync() method using a collection pipeline
This file contains 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
/** | |
The allocate_ids and remove_ids are from a multiselect so just an array of id's. | |
Trying to end up with a structure like : | |
[ | |
123 => ['is_accepted' => true], | |
345 => ['is_accepted' => true], | |
... | |
] | |
No matter how many variations of map/flatmap/values/blah I used I always either ended up | |
with a collection of collections, or had re-keyed the collection to something like : | |
[ | |
0 => ['is_accepted' => true], | |
1 => ['is_accepted' => true], | |
] | |
*/ | |
public function updateStudents(Request $request, $id) | |
{ | |
$project = Project::findOrFail($id); | |
$addIds = collect($request->allocate_ids); | |
$currentIds = $project->students->pluck('id'); | |
$removeIds = collect($request->remove_ids); | |
$newIds = $currentIds->merge($addIds)->diff($removeIds); // ->map/flatMap/argh | |
$items = []; | |
foreach ($newIds as $item) { | |
$items[$item] = ['is_accepted' => true]; | |
} | |
//dd($items); | |
$project->students()->sync($items); | |
return redirect()->route('project.show', $id); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks go to @adamwathan : https://gist.github.com/adamwathan/a04873b44a1dcd0f2b4257168499162c