From 9b31b48f37d9a7dd0e7a7fd0f27a9cef016771b0 Mon Sep 17 00:00:00 2001 From: Josef Citrine Date: Sun, 25 Sep 2016 15:07:20 +0100 Subject: [PATCH] Check if genre exists before creating a new one --- app/Commands/ParseTrackTagsCommand.php | 31 ++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/app/Commands/ParseTrackTagsCommand.php b/app/Commands/ParseTrackTagsCommand.php index bb035376..b5d7613f 100644 --- a/app/Commands/ParseTrackTagsCommand.php +++ b/app/Commands/ParseTrackTagsCommand.php @@ -126,10 +126,33 @@ class ParseTrackTagsCommand extends CommandBase * @return int */ protected function getGenreId(string $genreName) { - return Genre::firstOrCreate([ - 'name' => $genreName, - 'slug' => Str::slug($genreName) - ])->id; + $existingGenre = Genre::withTrashed() + ->where('name', $genreName)->first(); + + if ($existingGenre == null) { + // Has never existed, create new genre + + return Genre::create([ + 'name' => $genreName, + 'slug' => Str::slug($genreName) + ])->id; + } else { + // Exists in db, has it been deleted? + + $visibleGenre = Genre::where('name', $genreName)->first(); + + if ($visibleGenre == null) { + // This genre was deleted. Let's bring it back + // instead of creating a new one + + $existingGenre->restore(); + return $existingGenre->id; + } else { + // It's fine, just return the ID + + return $visibleGenre->id; + } + } } /**