How to Insert Multiple Records in Database Laravel

Hello Geek, We may need to insert multiple records into the database in some cases. Using Eloquent Model or Query Builder in Laravel, you can insert multiple records into the database.

Assume that one student can read multiple subjects and that you want to save the information of a student who reads multiple subjects in a different table called student subjects.

Use Laravel Eloquent Model or Query Builder to Insert Multiple Records in Database Laravel

In the following example, I used the multidimensional $createMultipleUsers array variable and DB::insert to insert multiple records. So, let’s take a look at how to insert multiple records in Laravel.

$createMultipleUsers = [
    ['name'=>'Admin','email'=>'admin@techvblogs.com', 'password' => bcrypt('TechvBlogs@123')],
    ['name'=>'Guest','email'=>'guest@techvblogs.com', 'password' => bcrypt('Guest@456')],
    ['name'=>'Account','email'=>'account@techvblogs.com', 'password' => bcrypt('Account@789')]
];

User::insert($createMultipleUsers); // Eloquent
\DB::table('users')->insert($createMultipleUsers); // Query Builder

Insert Multiple Records in a Database Using Laravel Seeder Laravel

You can create dummy data (with relations, etc.) using model Factories and faker to develop and test your app. For user generation testing, you must use the faker class. Let’s see how we can generate fake records with faker.

  1. Design a 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

All the best nerd!

Leave a Reply