Skip to content

Instantly share code, notes, and snippets.

@ohnotnow
Created June 7, 2016 16:08
Show Gist options
  • Save ohnotnow/20ae961fa8e2fc6c3d2cb12288be5684 to your computer and use it in GitHub Desktop.
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
/**
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);
}
@ohnotnow
Copy link
Author

ohnotnow commented Jun 7, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment