How can I create a laravel-seeder based on an array?
I have an array like this:
$positions = array(
array('industry_id' => '1', 'name' => 'developer'),
array('industry_id' => '1', 'name' => 'designer'),
array('industry_id' => '2', 'name' => 'project manager'),
array('industry_id' => '3', 'name' => 'manager'),
...etc, etc,...etc // there are like 150 entries
)
So instead of doing like this
Position::create([ 'industry_id' => '1', 'name' => 'developer' ]);
for each entry, I was hoping there might be another way to achieve that?
Advertisement
Answer
Option A)
$positions = array(
array('industry_id' => '1', 'name' => 'developer'),
array('industry_id' => '1', 'name' => 'designer'),
array('industry_id' => '2', 'name' => 'project manager'),
array('industry_id' => '3', 'name' => 'manager'),
....
);
foreach ($positions as $position) {
Position::create([
'industry_id' => $position['industry_id'],
'name' => $position['name'],
]);
}
Option B)
DB::table((new Position)->getTable())->insert($positions);
Note: Insert doesn’t automatically populate the timestamp columns.