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

sevmardi's avatar

Faker randomElements()

Now I know there is a thread around here deals with this, But I have tried every possible outcome and it did not work for me. I am not sure what I am doing wrong.

I have read and re-read the documentation, but still don't get it working!

Note: I am dealing with foreign key

Here is what I have.

class Documents extends Model
{
 protected $table = 'documents';

    protected $fillable = ['name', 'description', 'relative_path','supplier_id'];

    public function supplier()
    {
        return $this->hasOne('App\Models\Suppliers');
    }

class Suppliers extends Model
{
    protected $table = 'suppliers';

    protected $fillable = ['name','description'];

    protected $guarded = ['id'];

   public function documents()
    {
        return $this->belongsTo('App\Models\Documents');
    }
class DocumentsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker\Factory::create();

        //   I have tried ::lists('id) & lists()->all('id') and both did not work! 
        $suppliers = Supplier::all()->lists('id');
        foreach (range(1, 30) as $index)
        {
            Documents::create([
                'name' => $faker->name,
                'description' => $faker->text(5 ),
                'supplier_id' => $faker->randomElement($suppliers),

                'relative_path' => $faker->paragraph(1)
            ]);
        }
    }
}

Someone tell me what I am doing wrong here?

update: forgot to mention the error keeps pops up.

[ErrorException]                                                                                                            
  Argument 1 passed to Faker\Provider\Base::randomElements() must be of the type array, object given, 
0 likes
2 replies
sevmardi's avatar
sevmardi
OP
Best Answer
Level 7

issue solved!

lists('id')->all();

did the trick

joeljerushan's avatar

for updated version of Laravel <3 use

pluck('id')->all()
1 like

Please or to participate in this conversation.