Home >Database >Mysql Tutorial >How to Insert Multiple Rows into a Database Using Eloquent or the Query Builder in Laravel?
Efficiently Inserting Multiple Database Rows with Laravel's Eloquent and Query Builder
This guide demonstrates how to insert multiple rows into a database table using Laravel's Eloquent ORM and Query Builder. We'll focus on techniques for efficient bulk insertion from a single query's results.
Using Eloquent for Bulk Inserts
Eloquent's insert
method offers a streamlined way to perform bulk insertions. This approach automatically handles model mutators, including timestamps.
<code class="language-php">$data = [ ['user_id' => 'Coder 1', 'subject_id' => 4096], ['user_id' => 'Coder 2', 'subject_id' => 2048], // ... more data rows ]; Model::insert($data);</code>
Leveraging the Query Builder for Bulk Inserts
The Laravel Query Builder provides an alternative insert
method on the DB
facade. This method bypasses Eloquent's model mutators, offering a slightly faster, but less flexible, approach.
<code class="language-php">$data = [ ['user_id' => 'Coder 1', 'subject_id' => 4096], ['user_id' => 'Coder 2', 'subject_id' => 2048], // ... more data rows ]; DB::table('table_name')->insert($data);</code>
Both methods effectively handle bulk insertion of numerous rows, simplifying database interactions within your Laravel applications. Choose the method that best suits your needs, considering the need for model mutator functionality.
The above is the detailed content of How to Insert Multiple Rows into a Database Using Eloquent or the Query Builder in Laravel?. For more information, please follow other related articles on the PHP Chinese website!