Home >Database >Mysql Tutorial >How to Bulk Insert Multiple Rows with Eloquent or Query Builder in Laravel?
Using Eloquent/Fluent to batch insert multiple rows of data from a single query
Question:
You have a query that returns an array of user IDs and account IDs. How can I insert these rows into another table, making sure the resulting table has the following format:
<code>ID | user_id | subject_id 1 | 8 | 9 2 | 8 | 2</code>
Answer:
Laravel provides two methods for batch inserting data into tables: using Eloquent or Query Builder.
Eloquent method:
<code class="language-php">$data = [ ['user_id' => 8, 'subject_id' => 9], ['user_id' => 8, 'subject_id' => 2], ]; UserSubject::insert($data);</code>
Query Builder method:
<code class="language-php">DB::table('table')->insert($data);</code>
Both methods accept an associative array, where each array represents a row to be inserted. Mutators (such as timestamps) are called when using Eloquent methods, but not when using Query Builder methods.
The above is the detailed content of How to Bulk Insert Multiple Rows with Eloquent or Query Builder in Laravel?. For more information, please follow other related articles on the PHP Chinese website!