Randy_Johnson's avatar

Running a loop whilst seeding db

Hey I just tried running a loop whilst seeding my db. But the seed wasn't successful, even though everything ran fine the entries were never put inside the database.

Is it possible for me to do what I was?

Edit!?

Also I am unable to move the pagination to the bottom of the page. It just sits at the top no matter what I do.

0 likes
3 replies
Tray2's avatar

Sure it is. I do it with this code in my seeder.

 class AuthorsTableSeeder extends Seeder
{
    protected $authors = [
        [
            'first_name' => 'Robert',
            'last_name' => 'Jordan',
            'slug' => 'jordan-robert'
        ],
        [
            'first_name' => 'Matt',
            'last_name' => 'Stauffer',
            'slug' => 'stauffer-matt'
        ],
        [
            'first_name' => 'Brandon',
            'last_name' => 'Sanderson',
            'slug' => 'samderson-brandon'
        ]
    ];

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        foreach($this->authors as $author) { Author::create($author); }
    }
}
Randy_Johnson's avatar

No, I mean like this:

for($i = 0; $i > 100; $i ++)
{
DB::table('users')->insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('user'),
            'is_admin' => 0,
            'created_at' => date("Y-m-d H:i:s"),
            'updated_at' => date("Y-m-d H:i:s"),
        ]);
}
1 like
Tray2's avatar
Tray2
Best Answer
Level 74

Then you should use factories

$factory->define(App\Author::class, function (Faker $faker) {
    $firstName = $faker->firstName();
    $lastName = $faker->lastName();
    return [
        'first_name' => $firstName,
        'last_name' => $lastName,
        'slug' => Str::slug($lastName . ', ' . $firstName)
    ];
});
factory(Author::class)->create();

To create more than one just pass the number as a second argument.

factory(Author::class, 50)->create();

https://laravel.com/docs/6.x/database-testing#writing-factories

Please or to participate in this conversation.