How to add multiple data at once in laravel?

by wilmer.lemke , in category: PHP Frameworks , 6 months ago

How to add multiple data at once in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by ryleigh , 2 months ago

@wilmer.lemke 

To add multiple data at once in Laravel, you can use the insert method provided by Eloquent ORM. This method allows you to insert an array of data records into a database table in a single query, which can be more efficient than inserting each record individually. Here's an example of how to use the insert method to add multiple data at once:

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

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


In this example, we have an array of data records with the keys corresponding to the column names in the users table. We then use the insert method on the users database table to add all the records at once.


Note that when using the insert method, the data passed in must be an array of associative arrays, where each associative array represents a single record to be inserted.


You can also use Eloquent models to insert multiple records at once. To do this, you can simply create a new instance of the model for each record and then call the save() method on each instance. Here's an example:

1
2
3
4
5
6
7
$user1 = new User(['name' => 'John', 'email' => '[email protected]']);
$user2 = new User(['name' => 'Jane', 'email' => '[email protected]']);
$user3 = new User(['name' => 'Bob', 'email' => '[email protected]']);

$user1->save();
$user2->save();
$user3->save();


This approach is useful if you need to perform additional operations or validations on each record before saving it to the database.