Home > Backend Development > PHP Tutorial > How to Insert Multiple Rows in Laravel Using Eloquent or Query Builder?

How to Insert Multiple Rows in Laravel Using Eloquent or Query Builder?

Linda Hamilton
Release: 2024-11-22 17:26:15
Original
349 people have browsed it

How to Insert Multiple Rows in Laravel Using Eloquent or Query Builder?

Inserting Multiple Rows Using Fluent

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();
Copy after login

This query retrieves an array of results, such as:

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

To insert these results into another table, you can use the following techniques:

Eloquent Approach

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

Model::insert($data); // calls mutators including timestamps
Copy after login

Query Builder Approach

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

DB::table('table')->insert($data); // does not call mutators
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template