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
Release: 2025-01-12 20:07:44
Original
554 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template