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
Linda HamiltonOriginal
2024-11-27 08:05:10192browse

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);

Using insert() with Query Builder:

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

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

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!

Statement:
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