How to insert multiple rows in laravel?

Member

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

How to insert multiple rows in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by denis , 3 months ago

@domenico 

To insert multiple rows in Laravel, you can use the insert method on the model class. Here is an example of how you can insert multiple rows using Laravel's Eloquent ORM:

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

User::insert($data);


In the example above, we have an array $data containing multiple rows of data that we want to insert into the User model. We then use the insert method on the User model and pass the array as the argument to insert multiple rows into the database.


Make sure to define the fillable attributes on your model to allow mass assignment of data.