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-app

  2. Next, generate the Product model and a migration file by running:

    php artisan make:model Product -m

  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');
    }
    };

  4. Next, run the migration to create the `products` table:

    php artisan migrate

  5. Now, generate a factory for the Product model:

    php artisan make:factory ProductFactory –model=Product

  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),
    ];
    }
    }

  7. Next, generate a seeder for the Product model:

    php artisan make:seeder ProductsTableSeeder

  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();
    }
    }

  9. Finally. run the seeder using the following artisan command:

    php artisan db:seed –class=ProductsTableSeeder

  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 records

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);

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 PostSeeder

  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,
    ]);
    }
    }
    }

  3. Next, execute the seeder:

    php artisan db:seed –class=PostSeeder

    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

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 *

Never again lose customers to poor
server speed! Let us help you.

Privacy Preference Center

Necessary

Necessary cookies help make a website usable by enabling basic functions like page navigation and access to secure areas of the website. The website cannot function properly without these cookies.

PHPSESSID - Preserves user session state across page requests.

gdpr[consent_types] - Used to store user consents.

gdpr[allowed_cookies] - Used to store user allowed cookies.

PHPSESSID, gdpr[consent_types], gdpr[allowed_cookies]
PHPSESSID
WHMCSpKDlPzh2chML

Statistics

Statistic cookies help website owners to understand how visitors interact with websites by collecting and reporting information anonymously.

_ga - Preserves user session state across page requests.

_gat - Used by Google Analytics to throttle request rate

_gid - Registers a unique ID that is used to generate statistical data on how you use the website.

smartlookCookie - Used to collect user device and location information of the site visitors to improve the websites User Experience.

_ga, _gat, _gid
_ga, _gat, _gid
smartlookCookie
_clck, _clsk, CLID, ANONCHK, MR, MUID, SM

Marketing

Marketing cookies are used to track visitors across websites. The intention is to display ads that are relevant and engaging for the individual user and thereby more valuable for publishers and third party advertisers.

IDE - Used by Google DoubleClick to register and report the website user's actions after viewing or clicking one of the advertiser's ads with the purpose of measuring the efficacy of an ad and to present targeted ads to the user.

test_cookie - Used to check if the user's browser supports cookies.

1P_JAR - Google cookie. These cookies are used to collect website statistics and track conversion rates.

NID - Registers a unique ID that identifies a returning user's device. The ID is used for serving ads that are most relevant to the user.

DV - Google ad personalisation

_reb2bgeo - The visitor's geographical location

_reb2bloaded - Whether or not the script loaded for the visitor

_reb2bref - The referring URL for the visit

_reb2bsessionID - The visitor's RB2B session ID

_reb2buid - The visitor's RB2B user ID

IDE, test_cookie, 1P_JAR, NID, DV, NID
IDE, test_cookie
1P_JAR, NID, DV
NID
hblid
_reb2bgeo, _reb2bloaded, _reb2bref, _reb2bsessionID, _reb2buid

Security

These are essential site cookies, used by the google reCAPTCHA. These cookies use an unique identifier to verify if a visitor is human or a bot.

SID, APISID, HSID, NID, PREF
SID, APISID, HSID, NID, PREF