1

I want to insert multiple rows in a table, where the data collection I am inserting has a unique number. For example : I am inserting 2 row for a user_id number 1. My codes from controller is : I want to keep DB::table() instead of laravel eloquent

foreach($post_data['user_id'] as $key => $no){
        $set_base  = DB::table('package_user')
            ->Insert([
                'base_id' => $post_data['base_id'],
                'base_title' => $post_data['base_title'],
                'user_id' => $no,
                'package_id' => $post_data['package_id'],
                'plan_id' =>  $post_data['plan_id'],
                'currency' => $post_data['currency'],
                'payable_plan_amount' => $post_data['total_amount'],
                'created_at' =>  Carbon::now()

            ]);
    }

2 Answers 2

4

Please refer How to insert multiple rows from a single query using eloquent/fluent there is a solution for both eloquent and querybuilder

      $data = [
    ['user_id'=>'Coder 1', 'subject_id'=> 4096],
    ['user_id'=>'Coder 2', 'subject_id'=> 2048],
];
Model::insert($data); // Eloquent approach
DB::table('table')->insert($data); // Query Builder approach
Sign up to request clarification or add additional context in comments.

2 Comments

so we don't need any foreach loop ?
Yes you don't need foreach..if it's worked please accept the answer
0

You can also use fill() method if the model instance already created with the pre-defined populated datas.

<code>
    $modelObj = new Model();
    $modelCollection = collect($request->input())->all();
    $modelObj->fill($modelCollection);
    $modelObj->save();
</code>

Comments

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.