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

            ]);
    }
azim
  • 67
  • 2
  • 8

2 Answers2

3

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