Bulk Insertion in Laravel using eloquent ORM Bulk Insertion in Laravel using eloquent ORM laravel laravel

Bulk Insertion in Laravel using eloquent ORM


You can just use Eloquent::insert().

For example:

$data = array(    array('name'=>'Coder 1', 'rep'=>'4096'),    array('name'=>'Coder 2', 'rep'=>'2048'),    //...);Coder::insert($data);


We can update GTF answer to update timestamps easily

$data = array(    array(        'name'=>'Coder 1', 'rep'=>'4096',        'created_at'=>date('Y-m-d H:i:s'),        'modified_at'=> date('Y-m-d H:i:s')       ),    array(         'name'=>'Coder 2', 'rep'=>'2048',         'created_at'=>date('Y-m-d H:i:s'),         'modified_at'=> date('Y-m-d H:i:s')       ),    //...);Coder::insert($data);

Update:to simplify the date we can use carbon as @Pedro Moreira suggested

$now = Carbon::now('utc')->toDateTimeString();$data = array(    array(        'name'=>'Coder 1', 'rep'=>'4096',        'created_at'=> $now,        'modified_at'=> $now       ),    array(         'name'=>'Coder 2', 'rep'=>'2048',         'created_at'=> $now,         'modified_at'=> $now       ),    //...);Coder::insert($data);

UPDATE2: for laravel 5 , use updated_at instead of modified_at

$now = Carbon::now('utc')->toDateTimeString();$data = array(    array(        'name'=>'Coder 1', 'rep'=>'4096',        'created_at'=> $now,        'updated_at'=> $now       ),    array(         'name'=>'Coder 2', 'rep'=>'2048',         'created_at'=> $now,         'updated_at'=> $now       ),    //...);Coder::insert($data);


This is how you do it in more Eloquent way,

    $allintests = [];    foreach($intersts as $item){ //$intersts array contains input data        $intestcat = new User_Category();        $intestcat->memberid = $item->memberid;        $intestcat->catid= $item->catid;        $allintests[] = $intestcat->attributesToArray();    }    User_Category::insert($allintests);