How to Insert Multiple Records in Database Laravel 11

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:

  1. Using the insert() Method:
    The insert() 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);
  1. Using the create() Method with an Array of Data:
    If you’re working with Eloquent models, you can use the create() 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.

  1. Using the insertGetId() Method:
    If you need to retrieve the IDs of the inserted records, you can use the insertGetId() 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.

Leave a Reply