Home >Database >Mysql Tutorial >How to Insert Multiple Rows into a Database Using Eloquent or the Query Builder in Laravel?

How to Insert Multiple Rows into a Database Using Eloquent or the Query Builder in Laravel?

Susan Sarandon
Susan SarandonOriginal
2025-01-12 20:07:44554browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn