Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seed multiple custom rows/entries in ModelFactory Laravel

How can I seed multiple rows using ModelFactory in Laravel?

Inside ModelFactory.php I have the following code:

$factory->define(App\User::class, function (Faker $faker) {
    static $password;

    return [
        'name' => 'Admin',
        'Description' => 'Administrators have full access to everything.'
    ];
});

How can I add the following arrays, without using raw expressions?

[
    'name' => 'Admin',
    'description' => 'Administrators have full access to everything.',
],
[
    'name' => 'User',
    'description' => 'User have normal access.',
],

Thanks

like image 370
Nucleus Avatar asked Nov 07 '22 16:11

Nucleus


2 Answers

You can use sequence()

User::factory()->count(2)->sequence(['name' => 'admin'],['name' => 'user'])
->create()

example from laravel documentation

$users = User::factory()
            ->count(10)
            ->sequence(fn ($sequence) => ['name' => 'Name '.$sequence->index])
            ->create();

source https://laravel.com/docs/8.x/database-testing#sequences

like image 69
Moode Osman Avatar answered Nov 15 '22 05:11

Moode Osman


Let's say you want to add 100 users in your database.

Create a UserFactory.php in database/factories:

<?php

use Faker\Generator as Faker;

$factory->define(App\User::class, function (Faker $faker) {

    return [
        'name' => 'Admin',
        'Description' => 'Administrators have full access to everything.'
    ];
});

Then, in database/seeds/DatabaseSeeder.php:

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\User::class, 100)->create();
    }
}

You can find more details about seeding in the Laravel official documentation.

like image 21
louisfischer Avatar answered Nov 15 '22 05:11

louisfischer