Home >Backend Development >PHP Tutorial >How to Efficiently Insert Multiple Rows Using Eloquent or Query Builder in Laravel?
Inserting Multiple Rows with Eloquent/Fluent
You want to insert multiple rows into another table based on a query that retrieves data from a specific table. Let's understand how this can be achieved using Eloquent or the query builder.
To bulk insert data using Eloquent:
$data = [ ['user_id' => 'Coder 1', 'subject_id' => 4096], ['user_id' => 'Coder 2', 'subject_id' => 2048], // ... ]; Model::insert($data); // Calls mutators including timestamps
Alternatively, you can use the query builder:
DB::table('table')->insert($data); // Does not call mutators
In your case, you can modify the $query to retrieve the desired data and then insert it into the other table using one of the above methods.
Remember that you can dynamically determine the number of rows in $query using:
$rowCount = count($query);
This information can help you iterate through the rows if necessary.
The above is the detailed content of How to Efficiently Insert Multiple Rows Using Eloquent or Query Builder in Laravel?. For more information, please follow other related articles on the PHP Chinese website!