How to insert multiple records in table using laravel?

Member

by aubrey , in category: PHP Frameworks , a month ago

How to insert multiple records in table using laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lew , a month ago

@aubrey 

To insert multiple records in a table using Laravel, you can use the insert method provided by Eloquent. Here is an example code snippet to demonstrate how to insert multiple records:

1
2
3
4
5
6
7
$data = [
    ['name' => 'John Doe', 'email' => '[email protected]'],
    ['name' => 'Jane Smith', 'email' => '[email protected]'],
    ['name' => 'Bob Johnson', 'email' => '[email protected]'],
];

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


In this example, we have an array of data where each element represents a record to be inserted. We then call the insert method on the users table in the database and pass the array of data as an argument.


This will insert multiple records into the users table in a single query, which is more efficient than inserting records one by one.