Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Automatic_Minimum_61's avatar

how to do seeding in pivot table in laravel8.0???

hey guys,,, facing problem , I am not able to seed pivot table with factories in laravel??could you help me in getting the shit done??? It has three tables - user , events, event_user(pivot table) ?? these are my codes user model: public function events() { return $this->belongsToMany(Event::class); }

events model: public function users() { return $this->hasMany(User::class); }

Event_user seeder file: public function run() {

    $User =  User::inRandomOrder()->value('id');
    $Events = Event::inRandomOrder()->value('id');
    
    DB::table('event_user')->insert(array(
                
        'user_id' => $User,
        'event_id' => $Events,
        'note'     =>  Str::random(20),
        'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
        'updated_at' => Carbon::now()->format('Y-m-d H:i:s'),
    
    ));
    
}
0 likes
2 replies
CorvS's avatar

We are talking about a many-to-many relationship here, so your users() relationship is incorrect, you have to use belongsToMany(...) as well.

After that you can make use of the factory methods to create users, events and their relationship.

/* Create 10 users, each user having 5 events */
User::factory(10)->hasEvents(5)->create();

https://laravel.com/docs/8.x/database-testing#many-to-many-relationships

Please or to participate in this conversation.