Bulk Insertion in Laravel using eloquent ORM
Solution 1:
You can just use Eloquent::insert()
.
For example:
$data = [
['name'=>'Coder 1', 'rep'=>'4096'],
['name'=>'Coder 2', 'rep'=>'2048'],
//...
];
Coder::insert($data);
Solution 2:
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);
Solution 3:
This is how you do it in more Eloquent way,
$allinterests = [];
foreach($interests as $item){ // $interests array contains input data
$interestcat = new User_Category();
$interestcat->memberid = $item->memberid;
$interestcat->catid = $item->catid;
$allinterests[] = $interestcat->attributesToArray();
}
User_Category::insert($allintests);