2

How I can insert a list of ids with DB query without use foreach.

example with foreach :

$ids=[1,3,5];
foreach ($ids as $id) {
    DB::Table('user')->insert(['name'=>'test','user_id'=>$id]);
} 

1 Answer 1

1

You may use array_map;

$ids = [1, 3, 5];
$data = array_map(function ($id) {
    return ['name' => 'test', 'id' => $id];
}, $ids);

DB::table('user')->insert($data);
Sign up to request clarification or add additional context in comments.

1 Comment

This solution will make me connect to the database only once, Thanks

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.