Home >Backend Development >PHP Tutorial >How to Insert Multiple Rows in Laravel Using Eloquent or Query Builder?
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:
$data = [ ['user_id' => 8, 'subject_id' => 9], ['user_id' => 8, 'subject_id' => 2] ]; Model::insert($data); // calls mutators including timestamps
$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!