Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a quantity or other arguments to a Laravel seeder

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;
    }
}
like image 634
user-44651 Avatar asked Nov 27 '19 19:11

user-44651


2 Answers

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);
    }
}
like image 179
PtrTon Avatar answered Sep 18 '22 21:09

PtrTon


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 :)

like image 39
Medo Avatar answered Sep 19 '22 21:09

Medo