Skip to content

Instantly share code, notes, and snippets.

@shahednur
Forked from jarektkaczyk/tags.php
Created May 6, 2018 08:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shahednur/29d65a2c7642e228979462d63e54bd06 to your computer and use it in GitHub Desktop.
Save shahednur/29d65a2c7642e228979462d63e54bd06 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