Skip to content

Instantly share code, notes, and snippets.

@jarektkaczyk
Forked from AdrianKuriata/tags.php
Last active May 6, 2018 08:11
Show Gist options
  • Save jarektkaczyk/387f42facd517ea0ad7ad52ad1ba9ee1 to your computer and use it in GitHub Desktop.
Save jarektkaczyk/387f42facd517ea0ad7ad52ad1ba9ee1 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 store(Post $post)
{
$tags = [];
foreach ((array) request('tags') as $tag_name) {
$tags[] = Tag::firstOrNew(['name' => $tag_name]);
}
// a dla fanow adama wathana o jedna linijke mniej:
//
// $tags = collect((array) request('tags'))->map(function ($tag_name) {
// return Tag::firstOrNew(['name' => $tag_name]);
// });
$post->tags()->saveMany($tags);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment