Just push an item onto an array that looks exactly like the array you were passing to the insert method in the loop.
Insert eloquent array with arrays
Hello, i have little issue, or problem with inserting data. So i have form with three fields that are going to one table, and that is working, but i have 4th field which is array, so its declared as name=member_id[]. Now first i insert in primary table, and then i need to insert all of those member_id[] in second table, its one to many, but i dont want to make model for that second table. So i want to make it plain with insert method. Now i made it like this.
$group= Group::create([//stuff here]);
foreach ($request->input('member_id') as $member) {
DB::table('group_members')->insert(['member_id' => $member, 'group_id(fk)' => $group->id, 'custom'=>'0']);
}
and that works. But i have problem, if there is lets say 15 of those members, then 15 queries are executed, i feel like that is not needed. So i found that i can make it like this
DB::table('group_members')->insert([
['member_id' => $member, 'group_id(fk)' => $group->id, 'custom'=>'0']//first,
['member_id' => $member, 'group_id(fk)' => $group->id, 'custom'=>'0']//second, etc...
]);
and i hope that runs one query? So its better for resources. But i just cant manage to implement foreach like in my situation now, to make those arrays, and to place it in that insert. I tried to build string that looks like array, but that of course doesnt work. Is there any solution where it could be like
$group= Group::create([//stuff here]);
foreach ($request->input('member_id') as $member) {
// make arrays here
}
//and then
DB::table('group_members')->insert([
//place made arrays here
]);
Thanks very much. Im out of ideas already :(
You are adding your rows as strings rather than arrays.
Remove the quotes on the outside.
Please or to participate in this conversation.