Home  >  Article  >  Backend Development  >  How to Perform Bulk Inserts in Laravel Using Eloquent or Query Builder?

How to Perform Bulk Inserts in Laravel Using Eloquent or Query Builder?

DDD
DDDOriginal
2024-11-21 06:06:09523browse

How to Perform Bulk Inserts in Laravel Using Eloquent or Query Builder?

Performing Bulk Inserts with Eloquent or Fluent in Laravel

In Laravel, bulk inserting data is a breeze, and you can utilize either the Eloquent ORM or the fluent query builder to accomplish this.

Consider the following query:

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

This produces the output:

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

Your goal is to transfer this data into a separate table, resulting in a structure like:

ID | user_id | subject_id
1   | 8       | 9
2   | 8       | 2

To perform this bulk insert, you can employ one of the approaches outlined below:

Eloquent Approach:

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

UserSubject::insert($data);

This method utilizes mutators and timestamps.

Query Builder Approach:

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

DB::table('user_subject')->insert($data);

While this method is more direct, it doesn't invoke mutators.

The above is the detailed content of How to Perform Bulk Inserts 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