Last active
June 6, 2020 08:56
-
-
Save drjonnicholson/c209fc4083d7a1b27947fbb737abe218 to your computer and use it in GitHub Desktop.
Laravel 5.3 BulkInsert Trait
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Traits; | |
use Carbon\Carbon; | |
use DB; | |
/* | |
* Original idea from: https://github.com/laravel/framework/issues/1295#issuecomment-193025045 | |
*/ | |
trait BulkInsert | |
{ | |
/** | |
* Insert each item as a row. Does not generate events. | |
* | |
* @param array $items | |
* | |
* @return bool | |
*/ | |
public static function insertAll(array $items) | |
{ | |
$now = Carbon::now(); | |
$items = collect($items)->map(function (array $data) use ($now) { | |
return array_merge([ | |
'created_at' => $now, | |
'updated_at' => $now, | |
], $data); | |
})->all(); | |
return DB::table((new self)->getTable())->insert($items); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
dfgdfgdfg