Inserting multiple records into a database in Laravel 11 can be done using several methods, including the insert()
method, the create()
method with an array of data, or the insertGetId()
method for retrieving inserted IDs. Here’s how you can accomplish this:
- Using the
insert()
Method:
Theinsert()
method allows you to insert multiple records into a table at once by passing an array of data where each element represents a record.
$data = [
['name' => 'John', 'email' => 'john@example.com'],
['name' => 'Jane', 'email' => 'jane@example.com'],
// Add more records as needed
];
DB::table('users')->insert($data);
- Using the
create()
Method with an Array of Data:
If you’re working with Eloquent models, you can use thecreate()
method to insert multiple records by passing an array of data. This method creates model instances for each record and saves them to the database.
$data = [
['name' => 'John', 'email' => 'john@example.com'],
['name' => 'Jane', 'email' => 'jane@example.com'],
// Add more records as needed
];
User::create($data);
Ensure that the fillable
property is correctly defined in your model to allow mass assignment of the data.
- Using the
insertGetId()
Method:
If you need to retrieve the IDs of the inserted records, you can use theinsertGetId()
method. This method inserts the records into the table and returns an array of the inserted IDs.
$data = [
['name' => 'John', 'email' => 'john@example.com'],
['name' => 'Jane', 'email' => 'jane@example.com'],
// Add more records as needed
];
$insertedIds = DB::table('users')->insertGetId($data);
This is particularly useful when you need to perform subsequent operations with the inserted records.
Regardless of the method you choose, Laravel’s query builder or Eloquent ORM makes it simple to insert multiple records into a database efficiently and securely. Choose the method that best fits your project’s requirements and coding style.