Insert associative array into table with Laravel Eloquent

how to insert an associative array with Laravel Eloquent

I have this array

$data =  array (
  0 => 
    array (
      'first_id' => string '52763718329' 
      'second_id' => string '222122'
  ),
  1 => 
    array(
      'first_id' => string '527628573' (length=9)
      'second_id' => string '22210' (length=5)
   )
);

$model = new MyModel;
//$model->$data how do I pus data array?
$model->save();
+4
source share
3 answers
$data = $data->ToArray();

DB::table('mytable')->insert($data);
0
source

I ran into the same problem. Laravel 5 says it can handle multiple arrays but never works.

A simple solution is to simply loop and do an insert with foreach.

foreach($data as $insert){ 
            $id = \DB::table('tablename')->insertGetId($insert);

        }

You can also wrap it in a transaction, so if one of the elements fails, they will drop everything again.

//transaction start
\DB::beginTransaction();

foreach($data as $insert){ 
         $id = \DB::table('tablename')->insertGetId($insert);
         if(empty($id){    
            Log::error('Failed to insert row into database.');
            \DB::rollback();
            break;
   }
 }
//save everything
\DB::commit();
0
source
Its Work very well in Laravel 5 
if you have an Arry for example 

> item_array_m = array('name'=>'jhon','surname'=>'Doe');

In Eloquent the insert Query is save(); to insert in this way 

>  public function store(item_array_m)
>     {
>         var_dump($item_array_m);
>         $flight = new Carrito;
> 
>         $flight->name = $item_array_m["name"];     
>         $flight->surname = $item_array_m["surname"];
>  
> 
>         $flight->save();
>     }
-2

All Articles