In some scenarios, We need to insert multiple records into the database. In the laravel, You can insert multiple records into the database using Eloquent Model or Query Builder.
Suppose, one student can read many subjects and you want to store the information of a student who reads more than one subject and save it to a different table as student_subjects.
Use Laravel Eloquent Model or Query Builder to Insert Multiple Records in Database Laravel 9
In the example below, I use the multidimensional $createMultipleUsers
array variable and insert multiple records using DB::insert(). So let's see how to insert multiple records in laravel 9:
$createMultipleUsers = [
['name'=>'Admin','email'=>'[email protected]', 'password' => bcrypt('TechvBlogs@123')],
['name'=>'Guest','email'=>'[email protected]', 'password' => bcrypt('Guest@456')],
['name'=>'Account','email'=>'[email protected]', 'password' => bcrypt('Account@789')]
];
User::insert($createMultipleUsers); // Eloquent
\DB::table('users')->insert($createMultipleUsers); // Query Builder
Use Laravel Seeder to Insert Multiple Records in Database Laravel 9
You can generate dummy data using model Factories and faker to create fake data (with relations etc.) for developing and testing your app. Here you need to use the faker class for generation testing users. Let’s check out how we can use faker to generate fake records.
1. Create Laravel Seeder
php artisan make:seeder PostSeeder
2. Go to database/seeders
and edit the PostSeeder.php
file:
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Faker\Generator as Faker;
use App\Models\Post;
class PostSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$faker = Faker::create();
foreach (range(1,20) as $index) {
Post::create([
'title' => $faker->text,
'slug' => $faker->slug,
'description' => $faker->text,
'content' => $faker->content
]);
}
}
}
3. Use the db:seed command, Run the following command:
php artisan db:seed --class=PostSeeder
Thank you for reading this article.
Read Also: How to read environment variables in Node.js