0

I've got a foreign key of a user_id in my Listing table. In my ListingFactory I can put the user_id of a random user in that spot, but my user also has a is_seller bool. How can I make it so the query in my ListingFactory only gives me an array of users with is_seller=true? This is my code so far:

$factory->define(Listing::class, function (Faker $faker) {
    $randomSellerId = \App\User::where('is_seller', true)->pluck('id')->toArray();
    return [
        'seller_id' => $faker->randomElement($randomSellerId),
    ];
});

This code still puts all the users, including the ones with is_seller=false, into the $randomSellerId array

Max
  • 357
  • 1
  • 6
  • 16

2 Answers2

0

You Dont Need to Convert the Collection to array

Laravel Collection has out of the box method random

$factory->define(Listing::class, function (Faker $faker) {
    $allSellerId= \App\User::where('is_seller', true)->pluck('id');
    return [
        'seller_id' => $allSellerId->random(),
    ];
});
ManojKiran A
  • 5,896
  • 4
  • 30
  • 43
  • Thanks, I didn't know that, but it's still putting seller_ids of users with is_seller=false in the foreign key. – Max Aug 07 '19 at 05:49
0

You can get a random id using the following.

$randomId = \App\User::where('is_seller', true)->inRandomOrder()->value('id')
chanafdo
  • 5,016
  • 3
  • 29
  • 46