Home > Backend Development > PHP Tutorial > How Can I Insert Multiple Rows into a Database Table Using Eloquent in Laravel?

How Can I Insert Multiple Rows into a Database Table Using Eloquent in Laravel?

Linda Hamilton
Release: 2024-11-27 08:05:10
Original
191 people have browsed it

How Can I Insert Multiple Rows into a Database Table Using Eloquent in Laravel?

Inserting Multiple Rows with Eloquent in Laravel

You may encounter scenarios where you need to insert multiple rows into a database table from a single query. Eloquent provides convenient methods to achieve this.

To perform a bulk insert using Eloquent, consider the following:

Using insert() with Eloquent:

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

UserSubject::insert($data);
Copy after login

Using insert() with Query Builder:

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

DB::table('table')->insert($data);
Copy after login

Both approaches achieve the bulk insertion, resulting in a table with the desired structure:

ID user_id subject_id
1 8 9
2 8 2

Remember, UserSubject::insert() also calls mutators, such as timestamp manipulation. If mutators are not desired, use the DB::table() approach instead.

The above is the detailed content of How Can I Insert Multiple Rows into a Database Table Using Eloquent in Laravel?. 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