26

Is there a way to run the Laravel 5 seeder from within PHP rather than from the command line. The hosting I am using doesn't allow me to use the command line. Just to confirm I want to do the equivalent of this but in my app code:

php artisan db:seed
geoffs3310
  • 5,599
  • 11
  • 51
  • 104

3 Answers3

34

You can use the following method:

Artisan::call('db:seed');

To get the output of the last run command, you can use:

Artisan::output();
Bogdan
  • 43,166
  • 12
  • 128
  • 129
  • 2
    Related: How do you call this for a specific class? For example, if you want to call the equivalent of `php artisan db:seed --class=User`? I see that you pass an array to the `Artisan::call()` function, but I get an invalid argument exception when I use `Artisan::call('db:seed', ['class'=>'Users'])` saying "The 'class' argument does not exist." – Kirkland Aug 12 '15 at 18:55
  • 5
    Artisan::call('command:name', array('argument' => 'foo', '--option' => 'bar')); See https://laravel.com/docs/4.2/commands#calling-other-commands – Cameron Jun 27 '16 at 04:13
  • The answer below is a much better option – Thomas Nov 06 '17 at 13:20
  • 2
    @Kirkland, If you want to run specific seeder Class, try `Artisan::call('db:seed', ['--class' => 'YourSeederClass']);` – Sven Jan 15 '20 at 09:34
34

You can also call directly the Seeder class if needed. Just make sure you did a composer dump-autoload if you created your seeder manually.

From there code is very straightforward :

$seeder = new YourSeederClass();
$seeder->run();
elfif
  • 1,837
  • 17
  • 23
8

You can add parameters to the seeder on run

example

  $newSchool = School::create($data);

     $schoolMeals = new \MealSeeder();
     $schoolMeals->run($newSchool->id);

//school meal

 public function run($school = 1)
    {

        $time = Carbon::now();

        App\Meal::create([
            'school_id' => $school,
            'name' => 'Breakfast',
            'slug' => 'breakfast',
            'description' => 'Test Meal',
            'start_time' => $time->toTimeString(),
            'end_time' => $time->addMinutes(60)->toTimeString(),
        ]);
        App\Meal::create([
            'school_id' => $school,
            'name' => 'Lunch',
            'slug' => 'lunch',
            'description' => 'Test Meal',
            'start_time' => $time->toTimeString(),
            'end_time' => $time->addMinutes(60)->toTimeString(),
        ]);
        App\Meal::create([
            'school_id' => $school,
            'name' => 'Supper',
            'slug' => 'supper',
            'description' => 'Test Meal',
            'start_time' => $time->toTimeString(),
            'end_time' => $time->addMinutes(60)->toTimeString(),
        ]);
    }
Marvin Collins
  • 379
  • 6
  • 14