2

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.

2
  • Are you trying to insert four rows? Or one row with four values in a single column? Commented May 2, 2022 at 15:27
  • @AlexHowansky second one, I try to insert four rows with same $present value. Commented May 2, 2022 at 15:28

2 Answers 2

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); 

Test Laravel DB insert online

Sign up to request clarification or add additional context in comments.

3 Comments

I think that is better as syntax than a loop but come to the same thing. Maybe I can put the reference.
@Wtow, I'm not sure but consider eloquent insert with array process bulk insert instead multiple single inserts in loop
That is good idea to optimize database querry if not possible to optimize loop.
0

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]);
}

2 Comments

I have some for loop before this statement, so another for loop will increase complexity. Thank you for your answer, but I prefer to not use if it is possible.
You can not perform this insert without a loop somewhere. Stop micro-optimizing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.