217

I have the following query:

  $query = UserSubject::where('user_id', Auth::id())->select('subject_id')->get();

and as expected I get the following result:

[{"user_id":8,"subject_id":9},{"user_id":8,"subject_id":2}]

Is there a way of copying the above result into another table so that my table looks like this?

ID|user_id|subject_id
1 |8      |9
2 |8      |2

The problem I have is that the $query can expect any number of rows and so im unsure how to iterate through an unknown number of rows.

Billy
  • 2,823
  • 3
  • 16
  • 33
  • in case anyone still needs it: https://github.com/laravel/framework/issues/1295#issuecomment-193025045 – 4givN Feb 05 '20 at 10:39

3 Answers3

432

It is really easy to do a bulk insert in Laravel using Eloquent or the query builder.

You can use the following approach.

$data = [
    ['user_id'=>'Coder 1', 'subject_id'=> 4096],
    ['user_id'=>'Coder 2', 'subject_id'=> 2048],
    //...
];

Model::insert($data); // Eloquent approach
DB::table('table')->insert($data); // Query Builder approach

In your case you already have the data within the $query variable.

Halfacht
  • 924
  • 1
  • 12
  • 22
Kreshnik Hasanaj
  • 4,815
  • 1
  • 15
  • 18
  • I've tried that but unfortunately it's recognising my result as an object and not an array – Billy Apr 18 '15 at 23:29
  • 8
    Use the ->toArray() method on the object collection. – Kreshnik Hasanaj Apr 19 '15 at 00:20
  • 44
    It does not insert the timestamps. – guy_fawkes Dec 24 '15 at 06:49
  • 24
    add 'created_at'=>date('Y-m-d H:i:s'), 'modified_at'=> date('Y-m-d H:i:s') into your array. source: http://stackoverflow.com/a/26569967/1316842 – JR Tan Mar 03 '16 at 09:07
  • 13
    I wonder why Laravel doesn't have something like 'createMany' for this. – Abhishek Jul 04 '16 at 06:29
  • I believe this approach will not trigger on_save and on_create event handlers declared it the "boot" method. – Yevgeniy Afanasyev Dec 08 '16 at 22:31
  • 1
    @JoeriShoeby the OP wanted to do a batch `INSERT`. The `HasOneMany::saveMany()` doesn't do that. **Eloquent** [sources are self-explainatory](https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php#L234) – Peter Chaula Jan 07 '17 at 15:44
  • What if i have an array like this ` $array = ["54928328", "Carrie","Swift"]; ` ? – Rolly Aug 22 '17 at 16:33
  • 4
    How do I retrieve the ids? – Luvias Apr 22 '18 at 16:44
  • This technique is not inserting the created date. What should i do to insert created data with it? @KreshnikHasanaj – always-a-learner Sep 04 '18 at 10:29
  • @Luvias Not a very _Eloquent_ solution, but you could create a `insertGetIds` method, that just iterates over each element in the array of arrays and calls `insertGetId` and pushes that ID to an array, and then return that array of IDs. – JustCarty May 30 '19 at 07:58
  • i tried ->toArray() as well but still it considers the collection as object. ``` $data =DB::table(DB::raw('users'))->select('name','id','email')->where('name','like','Abdulh%')->orderBy('id')->get(); ``` DB::table('staff')->insert($data); – SeyT Feb 11 '21 at 09:44
  • 1
    what to do when my array size is bigger than 10 thousands? – ahmad-mohammadi Feb 21 '21 at 08:06
  • In this case of multiple records insertion, can i add a condition which checks if the id field value already exists in db table then that record will not be inserted. Please help. Eloquent updateOrCreate method works only for 1 record. – developer Sep 14 '21 at 11:02
  • This is the most applicable answer! How do we put this in DB:transaction? – JSTR Jan 24 '22 at 05:55
37

using Eloquent

$data = array(
    array('user_id'=>'Coder 1', 'subject_id'=> 4096),
    array('user_id'=>'Coder 2', 'subject_id'=> 2048),
    //...
);

Model::insert($data);
Vishal Varshney
  • 905
  • 6
  • 11
8

It is really easy to do a bulk insert in Laravel with or without the query builder. You can use the following official approach.

Entity::upsert([
    ['name' => 'Pierre Yem Mback', 'city' => 'Eseka', 'salary' => 10000000],
    ['name' => 'Dial rock 360', 'city' => 'Yaounde', 'salary' => 20000000],
    ['name' => 'Ndibou La Menace', 'city' => 'Dakar', 'salary' => 40000000]
], ['name', 'city'], ['salary']);
Rock Dial
  • 129
  • 1
  • 2