public function afterSave() { $tagIds = []; foreach ($this->tagNames as $name) { $tag = Tag::firstOrCreate(['name' => $name]); $tagIds[] = $tag->id; } $this->tags()->sync($tagIds); }
/** * Seed a book, some reviews, and some tags */ private function seed_books() { $book = Book::create(['title' => 'The Fellowship of the Ring', 'author' => 'Tolkien', 'price' => 9.949999999999999]); $review1 = Review::create(['book_id' => 1, 'review' => 'Best book ever, 5 stars!!!', 'stars' => 5]); $review2 = Review::create(['book_id' => 1, 'position' => 1, 'review' => 'Didn\'t really like it...', 'stars' => 2]); $tag1 = Tag::create(['name' => 'Epic']); $tag2 = Tag::create(['name' => 'High Fantasy']); $tag3 = Tag::create(['name' => 'Fiction']); $book->tags()->attach([1, 2, 3]); }