Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

pavlen's avatar

Insert array data with Eloquent

Hi,

this is function for saving data in DB.Work fine,but I am interesting is there Laravel way for this, instead foreach loop: Catnew value is array,posted from View.

     $checkBox = array();
         $checkBox = Input::get('catnew');
         $id = Input::get('id');
         
         $newSafety = new Extra;
         
         foreach($checkBox as $safety){
             
             $newSafety->offer_id = $id;
             $newSafety->car_id   = $safety;
             $newSafety->car      = 15;
             $newSafety->save();
         
         }

0 likes
3 replies
Corez64's avatar
Corez64
Best Answer
Level 37

If all you need to do is insert the data into a database just use the DB::insert, it should be more efficient.

$dataSet = [];
foreach ($checkBox as $safety) {
    $dataSet[] = [
        'offer_id'  => $id,
        'car_id'    => $safety,
        'car'       => 15,
    ];
}

DB::table('extra')->insert($dataSet);

This would not work if you need the models or listen to events when the new models are created, etc. As far as mass-creating the models and inserting them, I don't believe there is a "Laravel" way.

8 likes
monowar's avatar

table::insert[ 'offer_id'=> name; 'cart_id'=> name; 'cart_user'=> name; ]

Please or to participate in this conversation.