1

Hi all I am trying to insert multiple rows in a database at a time. Currently I can only save a single row at a time. I have done following:

public function addNewPriceRevision($data){
$PriceRevision=new ProductPriceRevision(
    [
        'product_id'=>$data->product_id,
        'invent_price'=>$data->invent_price,
        'revised_price'=>$data->revised_price,
        'effective_date'=>$data->effective_date,
        'deleted'=>$data->deleted,
        'remark'=>$data->remark,
        'user'=>$data->user,
        'date'=>$data->updated_at,

    ]
    );
 $PriceRevision->save();
 return Common::getJsonResponse(true, 'new price revision created successfully!', 200);
}
user3810794
  • 263
  • 2
  • 6
  • 23
  • Please check this answer http://stackoverflow.com/questions/12702812/bulk-insertion-in-laravel-using-eloquent-orm – Sajeewa Apr 19 '16 at 04:57

1 Answers1

0

Try to convert all objects to arrays and then create an array from multiple arrays:

$data = array($data1->toArray(), $data2->toArray());

If you need to add timestamps, you must do it manually:

$date = date('Y-m-d H:i:s');

$data1 = $data1->toArray();
$data1['created_at'] = $date;
$data1['updated_at'] = $date;

$data2 = $data2->toArray();
$data2['created_at'] = $date;
$data2['updated_at'] = $date;

$data = array($data1, $data2);

Then you could use mass assignment feature to create rows:

ProductPriceRevision::create($data);

And don't forget to fill $fillable array inside ProductPriceRevision model:

protected $fillable = [
    'product_id',
    'invent_price',
    'revised_price',
    'effective_date',
    'deleted',
    'remark',
    'user',
    'updated_at'
];
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279