Laravel Seeders: How to Pass Parameters?

preview_player
Показать описание
What if you want to seed some data, related to previously created data? Let me show you an example.

- - - - -
Support the channel by checking out our products:
Рекомендации по теме
Комментарии
Автор

This definitely isn't in the official documentation, but I've come across several occasions where it would be useful. Thank you again Povilas.

AugustoTitan
Автор

Love this, this actually helps a lot for some big projects where I needed to link together seeded data with ids!

Going to refactor my seeders into a tree structure and have nested calls like this.

You could go further and require command line arguments to get passed to it and throw errors if they're not set properly so that you can call groups of seeders easily!

gaffygaffy
Автор

I can see this is useful in a multi tenant app, the tenant can be created and passed into the seeder to associate every model with the tenant. Thanks!

MichaelPritchardRR
Автор

Thanks this was very helpful! I was about to look up how to share variables between seeders!!

thehonestabe
Автор

I could've used this yesterday – definitely implementing today!

travholt
Автор

Thanks Laravel Daily, I've been thinking how to implement this on my project. It's a big help.

jorembelen
Автор

Thank you very much for this, I was just thinking of how to implement this

aogunnaike
Автор

Really useful, thanks! Is it possible to pass arguments from the command line when using artisan db:seed?

papababis
Автор

is there a way to pass directly the parameter from command line? something like this PHP artisan db:seed --class=someClass --user-id=1?

Автор

Does this method require user_id to be set inside $fillable attribute?

PathOfDamn
Автор

->each(function ($user)
{

}); is use elequoent relationship to seed database

saravanasai
Автор

here is how i do that

$category = [
'arduino' => Category::where('category', 'Arduino Family')->first(),
'raspberry' => Category::where('category', 'Raspberry Family')->first(),
'esp' => Category::where('category', 'ESP Family')->first(),
];

User::factory(20)
->create()
->each(function () use ($category) {
Product::factory(rand(10, 20))
->has(View::factory(rand(1, 3)))
->has(Price::factory(rand(3, 10)))
->has(Sell::factory(rand(1, 3)))
->has(Image::factory(rand(1, 5)))
->for($category[array_rand($category, 1)])
->create();
});

neomn