Refactoring many to many relationship form logic
Hey all,
On my website I have Images and Collections, Users can add images to their collections using a checkbox list (Like how YouTube allows you to add videos to playlists).
As well as being able to add/remove the Image from each of their collections there is an input for if they want to create a new collection and add the Image to it. The checkboxes are named collection[{{ $collection->id }}] which then allows me to loop through an array of ids in the method.
Hopefully my code is commented well enough to make it easy to understand but if not feel free to ask any questions, would love to hear how else you might approach this as I feel it can be improved upon.
Thanks.
public function addImageToCollection(Request $request, Image $image) {
// If user is creating a new collection...
if($request->has('new-collection') && !empty($request->input('new-collection'))) {
$validator = Validator::make($request->all(), [
'new-collection' => 'max:70, min:3'
]);
if ($validator->fails()) {
return redirect($image->path())
->withErrors($validator)
->withInput();
}
$collection = Collection::create([
'name' => $request->input('new-collection'),
'user_id' => Auth::user()->id
]);
}
// Get collections input array from form...
$collections = isset($request->collection) ? $request->collection : [];
// If we just created a new collection...
if(isset($collection)) {
// Collection has been created, add to array...
$collections[$collection->id] = "on";
}
foreach(Auth::user()->collections as $collection) {
if(array_key_exists($collection->id, $collections)) {
// Redirect to the collection the image has been added to...
$collectionRedirect = $collection->path();
// Attach relationship...
$collection->images()->attach($image->id);
} else {
// Detach relationship...
$collection->images()->detach($image->id);
}
}
// If image has been added to a collection, redirect to the last one it was added to...
return (isset($collectionRedirect)) ? redirect($collectionRedirect . "/" . $image->slug) : back();
}
Please or to participate in this conversation.