This is giving me a big headache now. when adding tags to a product they are saving fine and both tags and taggables table are as should be, when editing that product and adding a new tag the tags table is updated correctly (no duplicates) however the taggables table has duplicate relationships.
public function update(Request $request, $slug)
{
$product = Product::where('slug', $slug)->firstOrFail();
$request->merge([
'slug' => str_slug($request->get('title'))
]);
$product->fill($request->input())->save();
//sync categories array
$product->categories()->sync($request->get('categories'));
// use helper function tags_to_array to turn string into array and remove whitespace
$tags = tags_to_array($request->get('tags'));
foreach($tags as $tag){
$tag = Tag::firstOrCreate(['name' => $tag]);
$product->tags()->attach($tag);
}
return redirect(route('dashboard.products'));
}
I add tag1,tag2 and save, then edit and add add tag3 (processes tag1,tag2,tag3) the tags table only has the three tags however the taggables table now has 5 rows.
tag_id taggable_id taggable_type
1 234 App\Product
2 234 App\Product
1 234 App\Product
2 234 App\Product
3 234 App\Product
Its like I need to check if the relation exists before attaching?