Seeding users and role_user data

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

Setting Up migration, factory and seeder of User model

//artisan commands 
php artisan make:seeder UserSeeder 
php artisan make:migration create_role_user_table 
// migration file
public function up(): void
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}
// UserFactory.php
public function definition(): array
{
    return [
        'name' => fake()->name(),
        'email' => fake()->unique()->safeEmail(),
        'email_verified_at' => now(),
        'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
        'remember_token' => Str::random(10),
    ];
}
// changing model User.php 
class User extends Authenticatable
{
    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }     
}
// UserSeeder.php
public function run(): void
{
    $admin = User::factory()->create();
    $admin->roles()->attach(Role::where('name', 'Administrator')->value('id'));

    $editor = User::factory()->create();
    $editor->roles()->attach(Role::where('name', 'Editor')->value('id'));
}

// migration file for role_user table   
public function up(): void
    {
        Schema::create('role_user', function (Blueprint $table) {
            $table->foreignId('user_id')->constrained();
            $table->foreignId('role_id')->constrained();  
        });
    }

// DatabaseSeeder.php
public function run(): void
{
    $this->call(PermissionSeeder::class);
    $this->call(RoleSeeder::class);
    $this->call(UserSeeder::class);  
}

Related Posts


Seeding clients and issues data

Adding client column in table

Storing issue in db table

Update issue

Showing user data and logout

Permission securing backend

Permission securing frontend