How to insert multiple record without loop in laravel?

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

How to insert multiple record without loop in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , 10 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' => 'john@example.com'],
    ['name' => 'Jane', 'email' => 'jane@example.com'],
    ['name' => 'Doe', 'email' => 'doe@example.com'],
];

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.

Related Threads:

How to update multiple record using laravel?
How to insert multiple emails in laravel?
How to insert multiple rows in laravel?
How to insert multiple records in table using laravel?
How to insert value into a record in mysql?
How to use for loop for insert in oracle?