I would like to pass an argument as to define how many records I want to create during database seeding, without having to edit the factory manually.
I have tried different variations on php artisan db:seed --class=UsersTableSeeder [using different args here]
I can't seem to find any documentation, so I don't know if that functionally exists. Does something like that exist?
class UsersTableSeeder extends Seeder
{
public $limit = null;
public function __construct($limit = 1) {
$this->limit = $limit;
}
public function run()
{
echo $this->limit;
}
}
From what I know there's no such thing as parameters for seeders, but you could implement it yourself. You could create a new command which accepts parameters and calls a seeder programmatically with those additional parameters.
Something like this should do the trick:
use Illuminate\Database\Seeder;
class UsersTableSeeder extends Seeder
{
public function run(int $limit)
{
echo $limit;
// Seed some stuff
}
}
namespace App\Console\Commands;
use Illuminate\Console\Command;
use UsersTableSeeder;
class SeedCommand extends Command
{
protected $signature = 'app:seed {limit}';
public function handle(UsersTableSeeder $seeder)
{
$limit = $this->argument('limit');
$seeder->run($limit);
}
}
you can ask for that limit before call any other seeders using
// DatabaseSeeder.php
$limit = $this->command->ask('Please enter the limit for creating something !!');
and then you can pass that limit to any additional seeders from 'DatabaseSeeder' like this
//DatabaseSeeder.php
$this->call(AnyAdditionalSeeder::class, false, compact('limit'));
then in 'AnyAdditionalSeeder' you can add parameter and name it $limit to the run() method like this
public function run($limit)
{
// you can access limit variable here
}
then when you run the command php artisan db:seed
it will ask you for the limit :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With