Home >Backend Development >PHP Tutorial >How to Insert Multiple Rows in Laravel Using Eloquent or Query Builder?

How to Insert Multiple Rows in Laravel Using Eloquent or Query Builder?

Linda Hamilton
Linda HamiltonOriginal
2024-11-22 17:26:15355browse

How to Insert Multiple Rows in Laravel Using Eloquent or Query Builder?

Inserting Multiple Rows Using Fluent

In Laravel, you can use Eloquent or the query builder to easily insert multiple rows of data into a database table using a single query.

Consider the following query:

$query = UserSubject::where('user_id', Auth::id())->select('subject_id')->get();

This query retrieves an array of results, such as:

[{"user_id":8,"subject_id":9},{"user_id":8,"subject_id":2}]

To insert these results into another table, you can use the following techniques:

Eloquent Approach

$data = [
    ['user_id' => 8, 'subject_id' => 9],
    ['user_id' => 8, 'subject_id' => 2]
];

Model::insert($data); // calls mutators including timestamps

Query Builder Approach

$data = [
    ['user_id' => 8, 'subject_id' => 9],
    ['user_id' => 8, 'subject_id' => 2]
];

DB::table('table')->insert($data); // does not call mutators

Both approaches allow you to insert multiple rows with a single query. The Eloquent approach calls model mutators and timestamps, while the query builder approach does not.

The above is the detailed content of How to Insert Multiple Rows in Laravel Using Eloquent or Query Builder?. 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