Home > Software engineering >  can't use assign role to User where i give factory
can't use assign role to User where i give factory

Time:01-27

I want to create users with factories and directly assign roles to them. However, I encountered an error while seeding. My Error was like there :

Method Illuminate\Database\Eloquent\Collection::assignRole does not exist.

Here is the code from my databaseSeeder.php :

$user = User::factory(10)->create()->assignRole('Admin');

That is my UserFactory code. This is default, I dont change anithing:

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
 */
class UserFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition()
    {
        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),
        ];
    }

    /**
     * Indicate that the model's email address should be unverified.
     *
     * @return static
     */
    public function unverified()
    {
        return $this->state(fn (array $attributes) => [
            'email_verified_at' => null,
        ]);
    }
}

This is my user model:

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
use PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

class User extends Authenticatable implements JWTSubject, HasMedia
{
     use HasApiTokens, HasFactory, Notifiable, HasRoles, InteractsWithMedia;

     /**
      * The attributes that are mass assignable.
      *
      * @var array<int, string>
      */
     protected $fillable = [
         'name',
         'e-mail',
         'passwords',
     ];
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Please help me, Thanks!

CodePudding user response:

Try assigning the role in your User factory callback like so:

class UserFactory extends Factory
{

...

public function configure()
{
    return $this->afterCreating(function (User $user) {
        $user->assignRole('Administrator');
    });
}

...

This method will be automatically run when you run the factory. After each create it will run assignRole on the created User model.

Use the factory like so:

User::factory()->count(10)->create();

https://laravel.com/docs/8.x/database-testing#factory-callbacks

  • Related