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!