Home > Article > Backend Development > How to Perform Bulk Inserts in Laravel Using Eloquent or Query Builder?
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!