Bulk Insertion In Laravel Using Eloquent ORM


Answer :

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); 

To whoever is reading this, check out createMany() method.

/**  * Create a Collection of new instances of the related model.  *  * @param  array  $records  * @return \Illuminate\Database\Eloquent\Collection  */ public function createMany(array $records) {     $instances = $this->related->newCollection();      foreach ($records as $record) {         $instances->push($this->create($record));     }      return $instances; } 

Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable