How to insert multiple records in table Laravel 5

How to insert multiple records in table Laravel 5

When you are working with hasMany relationship then you will need to insert multiple record at a time in a table.

Here you will find how many ways you can insert multiple record in a table and how to insert multiple records in a linked table(in case of hasMany relationship).

Syntax are :

  1. DB::table('your_table_name')->insert(array('array_data1','array_data2'....));


  1. DB::table('products')->insert(array(
  2. array("id"=>'1',"name"=>"expertphp","details"=>"Learning Portal"),
  3. array("id"=>'2',"name"=>"demo.expertphp.in","details"=>"Find running example"),
  4. );

OR


  1. $data1 = array("id"=>'1',"name"=>"expertphp","details"=>"Learning Portal");
  2. $data2 = array("id"=>'2',"name"=>"demo.expertphp.in","details"=>"Find running example");
  3. DB::table('products')->insert(array($data1,$data2));

This was example using DB query builder now i will insert multiple records using laravel eloquent model.


  1. $data = array(
  2. array("id"=>'1',"name"=>"expertphp","details"=>"Learning Portal"),
  3. array("id"=>'2',"name"=>"demo.expertphp.in","details"=>"Find running example"),
  4. //...
  5. );
  6. Product::insert($data); // Eloquent

Now I will tell you how to insert multiple records in table when you are working with hasMany relationship.

Suppose you have a table User and relatively a Comment table and User table has many comment and each comment belongs to user so when you are inserting multiple comments related models user then you can use saveMany method.


  1. $user = App\User::find(1);
  2. $user->comments()->saveMany([
  3. new App\Comment(['message' => 'First comment.']),
  4. new App\Comment(['message' => 'Second comment.']),
  5. ]);

Phone: (+91) 8800417876
Noida, 201301