Reputation:
I want to do a multiple insert in my Laravel project but I don't know how to do it. Do I need to loop it or there are any other method to do it? I'm a bit confused. I am using querybuilder.
Controller code.
if($request->smsn == 'on'){
$events->smsnotify = 1;
$numbers = \DB::table('users')
->where('school_id', '=', $sid->school_id)
->where('role', '=', $request->group_id)
->select('phone','name')
->get();
dd($numbers);
$sms = DB::table('sms')->insert([
'user_id' => $sid->id,
'school_id' => $sid->school_id,
'msg' => 'New Event '. $request->name,
'mobile_number' => $numbers,
'name' => 'Sample',
'isSend' => 1
]);
}
dump result
Collection {#552 ▼
#items: array:5 [▼
0 => {#550 ▼
+"phone": "+63 (928) 206-5706"
+"name": "Ayden Kutch"
}
1 => {#568 ▼
+"phone": "(0817) 447-1492"
+"name": "Ruthie Quigley"
}
2 => {#567 ▼
+"phone": "+63 (920) 203-3874"
+"name": "Alaina O'Kon"
}
3 => {#569 ▶}
4 => {#570 ▶}
]
}
I want to insert it in my sms
table like this format
+----+---------+---------------+---------------+--------+------------+------------+-----------+-------------+
| id | user_id | msg | mobile_number | isSend | created_at | updated_at | school_id | name |
+----+---------+---------------+---------------+--------+------------+------------+-----------+-------------+
| 8 | 13 | New Event | 123456 | 1 | NULL | NULL | 2 | Ayden Kutch |
+----+---------+---------------+---------------+--------+------------+------------+-----------+-------------+
In every name and number. It generates another row.
Upvotes: 3
Views: 399
Reputation: 112
This Work for me
$value = array();
foreach ($users as $user) {
$value = array(
'user_id' => $user->id,
'name' => $user->name,
'mobile_number' => $user->phone,
);
DB::table('users')->insert($data);
}
Upvotes: 2
Reputation: 50491
You can do multiple insert queries in a loop, or a single insert query with an array or arrays, but you will need to build that array first.
$data = [];
foreach ($numbers as $number) {
$data[] = [
'user_id' => $sid->id,
'school_id' => $sid->school_id,
'msg' => 'New Event',
'mobile_number' => $number->phone,
'name' => $number->name,
'isSend' => 1
];
}
DB::table('sms')->insert($data);
This builds an array of multiple records to be inserted together.
"You may even insert several records into the table with a single call to
insert
by passing an array of arrays. Each array represents a row to be inserted into the table"
Laravel 5.5 Docs - Query Builder - Inserts
Upvotes: 3