0

Below is my model factory.

$factory->define(App\Business::class, function (Faker\Generator $faker){
return [
'name' => $faker->bs,
'slug' => $faker->slug,
'address' => $faker->streetAddress,
'phone_no' => $faker->phoneNumber,
'mobile_no' => $faker->phoneNumber,
'email' => $faker->companyEmail,
'website' => $faker->domainName,
'latitude' => $faker->latitude,
'longitude' => $faker->longitude,
'location' => $faker->city,
'business_days_from' => $faker->dayOfWeek,
'business_days_to' => $faker->dayOfWeek,
'description' => $faker->text,
'user_id' => $faker->factory(App\User::class),
];

});

and This my database seeder class

class DatabaseSeeder extends Seeder
{
    public function run()
    {
        factory(App\Business::class, 300)->create();
    }
}

But when I execute php artisan db:seed ...it does not work..

What should be the workaround here..any help would be appreciated..

Raihan Mahmud
  • 78
  • 1
  • 11

2 Answers2

6

you can get all ids using pluck (lists is depricated for laravel >= 5.2)

$userIds = User::all()->pluck('id')->toArray();

and get a random id for FK column:

'user_id' => $faker->randomElement($userIds) 

You may also attach relationships to models using Closure attributes in your factory definitions.

    'title' => $faker->title,
    'content' => $faker->paragraph,
    'user_id' => function () {
        return factory(App\User::class)->create()->id;
    }
Ali Sherafat
  • 3,506
  • 2
  • 38
  • 51
0

I just found the workaround .. I replaced

'user_id' => $faker->factory(App\User::class),

with

'user_id' => $faker->randomElement(User::lists('id')->toArray()),

and that solves the problem for now..

Raihan Mahmud
  • 78
  • 1
  • 11
  • 2
    woked for me, used pluck() instead of lists() `'user_id' => $faker->randomElement(User::pluck('id')->toArray()),` –  Aug 20 '17 at 02:17