Reputation: 3903
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?
Upvotes: 0
Views: 1547
Reputation: 3918
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.
Upvotes: 2
Reputation: 8088
You can use foreach :
foreach ($positions as $position) {
Position::create(
[
'industry_id' => $position["industry_id"],
'name' => $position["name"],
]
);
}
it's not for big array/data but it's automatically create created_at
and updated_at
, other way use insert like Paul's answer
Upvotes: 0
Reputation: 12391
you can try insert()
by this created_at
and updated_at
is not automatically created so add manually
ref link https://laravel.com/docs/8.x/queries#inserts
Position::insert([
[
'industry_id' => '1',
'name' => 'developer',
"created_at" => now(),
"updated_at" => now()
],
[
'industry_id' => '1',
'name' => 'designer',
"created_at" => now(),
"updated_at" => now()
],
[
'industry_id' => '2',
'name' => 'project manager',
"created_at" => now(),
"updated_at" => now()
],
[
'industry_id' => '3',
'name' => 'manager',
"created_at" => now(),
"updated_at" => now()
],
]);
Upvotes: 1