以编程方式运行 Laravel 5 播种机而不是从 CLI
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28799779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run Laravel 5 seeder programmatically instead of from CLI
提问by geoffs3310
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 内部而不是从命令行运行 Laravel 5 播种机。我使用的主机不允许我使用命令行。只是为了确认我想在我的应用程序代码中执行与此等效的操作:
php artisan db:seed
回答by Bogdan
You can use the following method:
您可以使用以下方法:
Artisan::call('db:seed');
To get the output of the last run command, you can use:
要获取上次运行命令的输出,您可以使用:
Artisan::output();
回答by elfif
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.
如果需要,您也可以直接调用 Seeder 类。如果您手动创建了播种机,请确保您执行了 composer dump-autoload。
From there code is very straightforward :
从那里代码非常简单:
$seeder = new YourSeederClass();
$seeder->run();
回答by Marvin Collins
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(),
]);
}