6

I wrote factories for posts and categories and the work perfectly. But i can't find a way to populate the category_post table to test the ManyToMany relation between them.

How can I do that?

Rahimi0151
  • 395
  • 3
  • 11
  • Have you tried attaching the record? pivot tables filled with content when you attach the correct relationship between two entities. Refer to this on usage: https://laravel.com/docs/5.6/eloquent-relationships#many-to-many – Charis Jul 07 '18 at 14:39
  • 1
    Welcome to StackOverflow! Here we have many people eager to help, not all of them are telepaths. Since you have php tag, perhaps adding some code of what you tried might help. – TEH EMPRAH Jul 07 '18 at 15:31
  • I think this is what you are looking for: https://stackoverflow.com/questions/45269146/laravel-seeding-many-to-many-relationship – ineffable Jul 07 '18 at 15:55
  • where you want to populate in `view` or `database` ?? – Gabrielle-M Jul 08 '18 at 06:22

1 Answers1

6

The attach method accepts an array as a second parameter for saving pivot table data:

$post = Post::find(1);

$category = Category::find(1);

$post->categories()->attach($category->getKey(), ['foo' => 'bar']);
Brian Lee
  • 17,904
  • 3
  • 41
  • 52