Seeding clients and issues data

This tutorial is part of this mini project on Laravel vue spa. To see all the sections of this project click here

Step 01: Setting Up migration, factory and seeder of Client model

//artisan commands 
php artisan make:model Client -mfs
// migration file for clients table
public function up(): void
{
    Schema::create('clients', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->timestamps();
    });
}
// ClientFactory.php
public function definition(): array
{
    return [
        'name' => fake()->text(20),
    ];
}
// changing model Client.php 
class Client extends Model
{
    use HasFactory;

    protected $fillable = ['name'];

    public function issues()
    {
        return $this->hasMany(Issue::class);
    }      
}
// ClientSeeder.php (first approach with fixed number of issues rows per client row)
public function run(): void
{        
    \App\Models\Client::factory(20)
    ->has(\App\Models\Issue::factory(100))
    ->create();         
}
// ClientSeeder.php (second approach with varying number of issues (from 1 to 5) rows per client row)
public function run(): void
{        
    
    \App\Models\Client::factory(10)->create()->each( function($cl) {
        $cl->issues()->saveMany(
            \App\Models\Issue::factory(rand(1,5))->make()
        );
    });        
}
// DatabaseSeeder.php
public function run(): void
{
    $this->call(PermissionSeeder::class);
    $this->call(RoleSeeder::class);
    $this->call(UserSeeder::class);  
    $this->call(ClientSeeder::class);
}

Step 02: Setting Up migration, factory of Issue model

//artisan commands 
php artisan make:model Issue -mf
php artisan make:migration add_client_id_to_issues_table //if we were to add client_id later to issues table
// migration file for issues table
public function up(): void
{
    Schema::create('issues', function (Blueprint $table) {
        $table->id();
        $table->foreignId('client_id')->constrained();
        $table->string('title');
        $table->longText('description');             
        $table->timestamps();
    });
}
//IssueFactory.php 
public function definition(): array
{
    return [
        'title' => fake()->text(20),
        'description' => $this->faker->paragraphs(5, true),
    ];
}
// Changing Model Issue.php 
class Issue extends Model
{
    use HasFactory;

    protected $fillable = ['title', 'description', 'client_id'];

    public function client()
    {
        return $this->belongsTo(Client::class);
    }     
}

Related Posts


Seeding users and role_user data

Adding client column in table

Storing issue in db table

Update issue

Showing user data and logout

Permission securing backend

Permission securing frontend