0

I have 3 tables Applicant,Skills and Applicant_skill. Here Applicant_skill is the pivot table. One Applicant has many Skills. I am trying to write factory like below.

**ApplicantSkillFactory.php**

<?php

use Faker\Generator as Faker;

$factory->define(App\Applicant_skill::class, function (Faker $faker) {
    return [
        'applicant_id' => \App\Applicant::all()->random()->id,
        'skill_id' => \App\Skills::all()->random()->id,
    ];
});

ApplicantsTableSeeder.php

<?php

use Illuminate\Database\Seeder;

class ApplicantsTableSeeder extends Seeder
{
    public function run()
    {
        factory(App\Applicant::class,20)->create()->each(function ($u) {
            $u->Applicant_skill()->associate(factory(App\Applicant_skill::class)->make());
        });
    }
}

Now how can I seed those 3 tables ?

abu abu
  • 6,599
  • 19
  • 74
  • 131
  • 1
    well that is not how you normally use a pivot table. its usually create applicants. create skills. attach. https://laravel.com/docs/eloquent-relationships#updating-many-to-many-relationships – JoshKisb Mar 01 '18 at 04:39
  • Thanks @JoshKisb for your reply. Actually I am new in Factory and seeding. Could please you help me with some sample code ? Thanks. – abu abu Mar 01 '18 at 04:42

1 Answers1

4

There is no need for Applicant_skill factory
Simply get random id from skills when creating applicants and attach it

ApplicantsTableSeeder.php

<?php

use Illuminate\Database\Seeder;

class ApplicantsTableSeeder extends Seeder
{
    public function run()
    {
        factory(App\Applicant::class,20)->create()->each(function ($a) {
            $a->Applicant_skill()->attach(
                \App\Skills::all()->random()->id
            );
        });
    }
}
JoshKisb
  • 742
  • 7
  • 9