'Laravel database insert with combining array and string
I should insert an array such as $attendanceList = [18354012,18354013,18354014,18354015]
and $present = "FALSE"
and same for all item of $attendanceList
. As you see $attendanceList
is array but $present
is String
.
When I insert like DB::table("attendance")->insert(["id"=>$attendanceList,"present"=>"FALSE"])
returns error.
What should I do? Pairing all item of $attendanceList
and $present
or there are another ways?
Note: I don't want to use loop if it is possible.
Solution 1:[1]
You can prepare array from your data and do bulk insert in one query:
<?php
$attendanceList = [18354012,18354013,18354014,18354015];
$present = "FALSE";
$insertData = array_map(
fn($el)=>['id'=>$el, 'present'=>$present],
$attendanceList
);
$db::table("attendance")->insert($insertData);
Solution 2:[2]
I'm not sure why you don't want to use a loop. If you want to insert four separate rows, you're going to need one:
foreach ($attendanceList as $id) {
DB::table("attendance")->insert(["id" => $id,"present" => $present]);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Slava Rozhnev |
Solution 2 | Alex Howansky |