DEV Community

Cover image for Laravel 8 Factories, Seeder
shani singh
shani singh

Posted on • Edited on

Laravel 8 Factories, Seeder

In this post i am going to explain about creating dummy data in database by using Laravel Factory and Seed The Database by using Database Seeder.

To generate model factory run the command below.



php artisan make:factory UserFactory --model=User


Enter fullscreen mode Exit fullscreen mode

This will generate file in database/dactory/UserFactory.php

Now let's add fake data for each column.



<?php

namespace Database\Factories;

use App\Models\User;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
use Illuminate\Database\Eloquent\Factories\Factory;

class UserFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = User::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' => $this->faker->name(),
            'email' => $this->faker->unique()->safeEmail(),
            'email_verified_at' => now(),
            'password' => Hash::make('password'),
            'remember_token' => Str::random(10),
        ];
    }
}



Enter fullscreen mode Exit fullscreen mode

Now Add a seeder For UserTable by running command below.



php artisan make:seed UserTableSeeder


Enter fullscreen mode Exit fullscreen mode

This command generate a file in database/seeders/UserTableSeeder.php

Next Update the run function of seeder file.



<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\User;

class UserTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        User::factory()->count(50)->create();
    }
}



Enter fullscreen mode Exit fullscreen mode

Now Run the command below to seed the data,



php artisan db:seed --class=UserTableSeeder


Enter fullscreen mode Exit fullscreen mode

The Output result for users listing will be like.
Users List

You can access this code on TechTool India Github Repo.

You can watch the explanation video for more clarity.

To Read about Laravel Free Admin Panel

Thank You for Reading

In case of any query related to LARAVEL.
Reach Out To me.
Twitter
Instagram
TechToolIndia

Top comments (1)

Collapse
 
hrithikbansal profile image
Hrithik Bansal

Informative 💯