Using Seeder and factory to create dummy data for User, Post and Comment model

Step 01: create fresh laravel project

composer create-project laravel/laravel postcomment


Step 02
: Setting Up migration, factory of Post model and migration, factory, seeder of Comment model

php artisan make:model Post -mf
php artisan make:model Comment -mfs

Step 03
: Specifying migration definition in database\migrations\2022_07_31_183018_create_posts_table.php

Schema::create('posts', function (Blueprint $table) {
    $table->id();
$table->foreignId('user_id')->constrained();
$table->string('title');
$table->text('post_text');
$table->timestamps(); });


Then, specifying definition for database\migrations\2022_08_01_145902_create_comments_table.php

Schema::create('comments', function (Blueprint $table) {
   $table->id();
$table->foreignId('user_id')->constrained();
$table->foreignId('post_id')->constrained();
$table->text('comment_text');
$table->timestamps(); });


Step 04
: Specifying column rules for Post model in PostFactory.php

use App\Models\Post;

protected $model = Post::class;

public
function definition() { return [ 'title' => $this->faker->text(50), 'post_text' => $this->faker->text(500), ]; }


Then, specifying column rules for Comment model in CommentFactory.php

use App\Models\Comment;

protected $model = Comment::class;

public
function definition() { return [ 'user_id' => rand(1,100),
'post_id' => rand(1,10000),
'comment_text' => $this->faker->text(500), ]; }


Step 05
: Creating UserSeeder.php using artisan command

php artisan make:seeder UserSeeder


Step 06
: Specifying definition of UserSeeder.php

public function run()
{
	User::factory(100)
	->has(Post::factory(100))
	->create();
}


Then, specifying CommentSeeder

public function run()
{
   Comment::factory(50000)->create();
}

Step 07
: Running UserSeeder and CommentSeeder using run() method in DatabaseSeeder.php,  to run seeding data for user, post and comment table.

// DatabaseSeeder.php

$this->call([ UserSeeder::class,
CommentSeeder::class, ]);

Relations in these seeding and factories are mentioned below.

1. user hasMany posts
2. post belongsTo user
3. Comment belongsTo user and post
4. User hasMany comments
5. Post hasMany comments

//In User.php 

public function posts()
{
return $this->hasMany(Post::class);
}

public function comments()
{
return $this->hasMany(Comment::class);
}
//In Post.php public function user() { return $this->belongsTo(User::class); }


Step 8
: Finally running following artisan command to run migration and seeding database tables.

php artisan migrate:fresh --seed


Execution of above command, in Users table there will be 100 users created and in Posts table there will be 100 posts for each user. So in total there will be 10000 posts.

Lastly, for comments table there will be 50000 comments.

Related Posts