Maybe take a look at how its done in this spatie package :)
Feb 13, 2023
2
Level 5
There must be a better way to do this...
I have a piece of UI that allows the user to add tags to content. The UI singularly allows the user to add tags that are already associated with their account AND create new tags from scratch, in the same input.
This is pretty common functionality that you see around the internet all the time. I thought it would be really straight forward...
I have it working but I thought I could utilise firstOrNew / firstOrCreate but I just couldn't get that to work for various reasons.
Here's what I have, and it all works. Could it be better?
// These are the tags that get passed in from the form. Some will exist already and some won't
$tags = json_decode($request->tags);
$user = Auth::user();
$track_token = $request->track_token;
//Delete all current tags for this track
TrackTag::query()->where('track_token', $track_token)->delete();
if($request->tags) {
foreach ($tags as $tag) {
// Update all tags associated with this user / artist
$updatetags = Tag::query()->where(
['tag' => $tag->value],
['user_id' => $user->id],
)->first();
if (!$updatetags) {
$newtag = new Tag();
$newtag->tag = $tag->value;
$newtag->token = Str::uuid();
$newtag->user_id = $user->id;
$newtag->status = 1;
$newtag->save();
}
// Re-write all tags associated with this track
$newTrackTags = new TrackTag();
$newTrackTags->track_token = $track_token;
$newTrackTags->tag_token = $newtag->token ?? $updatetags->token;
$newTrackTags->user_id = $user->id;
$newTrackTags->status = 1;
$newTrackTags->save();
}
}
Please or to participate in this conversation.