Bobcares

How to Seed Multiple Records in Laravel

by | Jun 12, 2024

Learn how to seed Multiple Records in Laravel. Our Laravel Support team is here to help you with your questions and concerns.

How to Seed Multiple Records in Laravel

Did you know that seeding your database with test data is a key step in developing reliable applications?

In this blog, we will explore two methods to insert multiple records into our Laravel database:

  • Using Laravel factories and seeders
  • Using Eloquent Model or Query Builder directly.

Method 1: Using Laravel Factories and Seeders

  1. First, create a new Laravel project. Open a terminal and run:
    composer create-project laravel/laravel product-seeder-app
    cd product-seeder-appCopy Code
  2. Next, generate the Product model and a migration file by running:
    php artisan make:model Product -mCopy Code
  3. Then, open the newly created migration file and define the `up()` and `down()` methods as follows:
    // database/migrations/2023_12_02_173227_create_products_table.php
    <?php
    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;
    return new class extends Migration
    {
    /**
    * Run the migrations.
    */
    public function up(): void
    {
    Schema::create('products', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->text('description');
    $table->decimal('price', 8, 2);
    $table->timestamps();
    });
    }
    /**
    * Reverse the migrations.
    */
    public function down(): void
    {
    Schema::dropIfExists('products');
    }
    };
    Copy Code
  4. Next, run the migration to create the `products` table:
    php artisan migrateCopy Code
  5. Now, generate a factory for the Product model:
    php artisan make:factory ProductFactory –model=ProductCopy Code
  6. Then, define the attributes and their respective fake data in the ProductFactory:
    
    // database/factories/ProductFactory.php
    <?php
    use App\Models\Product;
    use Illuminate\Database\Eloquent\Factories\Factory;
    class ProductFactory extends Factory
    {
    protected $model = Product::class;
    public function definition()
    {
    return [
    'name' => $this->faker->sentence(2),
    'description' => $this->faker->sentence(4),
    'price' => $this->faker->randomFloat(2, 10, 1000),
    ];
    }
    }
    Copy Code
  7. Next, generate a seeder for the Product model:
    php artisan make:seeder ProductsTableSeederCopy Code
  8. After that, use the factory to seed multiple rows in the ProductsTableSeeder:
    // database/seeders/ProductsTableSeeder.php
    <?php
    namespace Database\Seeders;
    use App\Models\Product;
    use Illuminate\Database\Seeder;
    class ProductsTableSeeder extends Seeder
    {
    /**
    * Run the database seeds.
    */
    public function run(): void
    {
    Product::factory()->count(10)->create();
    }
    }
    Copy Code
  9. Finally. run the seeder using the following artisan command:
    php artisan db:seed –class=ProductsTableSeederCopy Code
  10. Now, verify the seeded data by checking the contents of the `products` table. We can use a command-line MySQL client or tools like HeidiSQL (Windows) or Sequel Ace (Mac).

    We have successfully generated 10 product records. We can generate more by adjusting the count in the seeder:

    Product::factory()->count(100000)->create(); // Generate a hundred thousand recordsCopy Code

Method 2: Inserting Multiple Records Directly

We can insert multiple records into the database using an array of data. here is an example of inserting multiple user records:


$createMultipleUsers = [
['name' => 'Admin', 'email' => 'admin@bobcares.com', 'password' => bcrypt('TechvBlogs@123')],
['name' => 'Guest', 'email' => 'guest@bobcares .com', 'password' => bcrypt('Guest@456')],
['name' => 'Account', 'email' => 'account@bobcares .com', 'password' => bcrypt('Account@789')],
];
// Using Eloquent
User::insert($createMultipleUsers);
// Using Query Builder
\DB::table('users')->insert($createMultipleUsers);
Copy Code

Alternatively, we can use Laravel seeders with faker to generate dummy data. Here’s how to do it:

  1. Generate a seeder for the Post model:
    php artisan make:seeder PostSeederCopy Code
  2. Then, edit the PostSeeder.php file to use faker for generating fake data:
    // database/seeders/PostSeeder.php
    <?php
    namespace Database\Seeders;
    use Illuminate\Database\Seeder;
    use Faker\Factory as Faker;
    use App\Models\Post;
    class PostSeeder extends Seeder
    {
    /**
    * Run the database seeds.
    */
    public function run(): void
    {
    $faker = Faker::create();
    foreach (range(1, 20) as $index) {
    Post::create([
    'title' => $faker->text,
    'slug' => $faker->slug,
    'description' => $faker->text,
    'content' => $faker->text,
    ]);
    }
    }
    }
    Copy Code
  3. Next, execute the seeder:
    php artisan db:seed –class=PostSeederCopy Code

    If we use the `insert` method, we will lose special Eloquent functionalities like timestamps and model events:

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

By following these methods, you can efficiently seed your Laravel database with multiple records, ensuring your application is well-prepared for development and testing.

[Need assistance with a different issue? Our team is available 24/7.]

Conclusion

By following these methods, we can efficiently seed your Laravel database with multiple records, ensuring our application is well-prepared for development and testing.

In brief, our Support Experts demonstrated how to seed Multiple Records in Laravel.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Speed issues driving customers away?
We’ve got your back!