Home > Article > Backend Development > How Can I Insert Multiple Rows into a Database Using Eloquent or the Query Builder?
Insert Multiple Rows Simultaneously with Eloquent or Fluent
This inquiry explores how to insert multiple rows into a database using a single query within the Eloquent (or fluent) framework. The given example retrieves data using UserSubject::where('user_id', Auth::id())->select('subject_id')->get();. However, the desired output requires inserting this data into a separate table with a specific column structure.
Solution:
Bulk inserting data is conveniently facilitated by Eloquent or the query builder. Consider the following techniques:
Utilize Model::insert($data); to insert multiple rows. This approach incorporates mutators, including timestamps.
Employ DB::table('table')->insert($data); to insert rows without calling mutators.
Example:
Given an array of row data:
$data = [ ['user_id'=>'Coder 1', 'subject_id'=> 4096], ['user_id'=>'Coder 2', 'subject_id'=> 2048], //... ];
Inserting them using Eloquent:
Model::insert($data);
Inserting them using the Query Builder:
DB::table('table')->insert($data);
The above is the detailed content of How Can I Insert Multiple Rows into a Database Using Eloquent or the Query Builder?. For more information, please follow other related articles on the PHP Chinese website!