"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Insert Multiple Rows into a Database Using Eloquent or the Query Builder?

How Can I Insert Multiple Rows into a Database Using Eloquent or the Query Builder?

Published on 2024-12-21
Browse:174

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:

  • Eloquent Approach:

Utilize Model::insert($data); to insert multiple rows. This approach incorporates mutators, including timestamps.

  • Query Builder Approach:

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);
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3