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 :
- DB::table('your_table_name')->insert(array('array_data1','array_data2'....));
- DB::table('products')->insert(array(
- array("id"=>'1',"name"=>"expertphp","details"=>"Learning Portal"),
- array("id"=>'2',"name"=>"demo.expertphp.in","details"=>"Find running example"),
- );
OR
- $data1 = array("id"=>'1',"name"=>"expertphp","details"=>"Learning Portal");
- $data2 = array("id"=>'2',"name"=>"demo.expertphp.in","details"=>"Find running example");
- DB::table('products')->insert(array($data1,$data2));
This was example using DB query builder now i will insert multiple records using laravel eloquent model.
- $data = array(
- array("id"=>'1',"name"=>"expertphp","details"=>"Learning Portal"),
- array("id"=>'2',"name"=>"demo.expertphp.in","details"=>"Find running example"),
- //...
- );
- 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.
- $user = App\User::find(1);
- $user->comments()->saveMany([
- new App\Comment(['message' => 'First comment.']),
- new App\Comment(['message' => 'Second comment.']),
- ]);