Skip to content

Instantly share code, notes, and snippets.

@AdrianKuriata
Last active November 1, 2016 10:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AdrianKuriata/490619b03b9910f15d9bd9f9a9c07100 to your computer and use it in GitHub Desktop.
Save AdrianKuriata/490619b03b9910f15d9bd9f9a9c07100 to your computer and use it in GitHub Desktop.
This is optimization tags for ManyToMany relationship with Post model for attaching not existing tags.
public function storePost(Request $request)
{
$notexistsTags = array();
$existsTags = Tag::whereIn('id', $request->input('tag_name'))->get();
foreach($request->input('tag_name') as $tag_name) {
// Check if tag currently exist in database
foreach($existsTags as $tag) {
$match = false;
if($tag_name == $tag->id) {
$match = true;
break;
}
}
// If tag from user's input was not matched to tag in database
// add it to the $notexistsTags array.
if(!$match) {
$notexistsTags['tag_name'] = $tag_name;
}
}
//Get a pluck ID exists tags
$exTags = $existsTags->pluck('id')->toArray();
//Create not exists tags
$createdTags = Tag::create($notexistsTags);
//Get ID tags which was created
$getTagsId = Tag::whereIn('id', $createdTags)->pluck('id')->toArray();
//Add exists and not exists tags to one array for save it with attach posts
$tagsToAdd = array_merge($exTags, $getTagsId);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment