How to insert multiple record without loop in laravel?

by raven_corwin , in category: PHP Frameworks , 3 months ago

How to insert multiple record without loop in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , 3 months ago

@raven_corwin 

You can use the insert method provided by Laravel's query builder to insert multiple records without using a loop.


Here is an example of how you can insert multiple records at once:

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

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


In this example, we have an array of data with multiple records that we want to insert into the users table. We simply pass the array of data to the insert method along with the table name and Laravel will insert all the records at once without the need for a loop.