jones
jones

Reputation: 1453

Laravel 6 Factory, can't access relationship methods after using state

Suppose I have a user factory to create user, for specific user I want to add more information, for this I've defined state inside factory, but if I use state, then I can not call related method of user after user creation suppose I should assign role to the user using assignRole($role). Following is my UserFactory.php

$factory->define(User::class, function (Faker $faker) {
  return [
    'email' => $faker->unique()->safeEmail,
    'email_verified_at' => now(),
    'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
    'remember_token' => Str::random(10),
    'first_name' => $faker->name,
    'last_name' => $faker->lastName,
    'phone' => $faker->phoneNumber,
    'password' => bcrypt('12345678'),
 ];
});

$factory->state(User::class, 'Admin', function (Faker $faker) {
$country = factory(Country::class)->create();
$province = factory(Province::class)->create();
static $afghanistanId = 1;
$admin= [
    'about' => $faker->sentence($nbWords = 20, $variableNbWords = true),
    'address' => $faker->address,
];
if($country->id  == $afghanistanId) {
    $admin['province_id'] = $province->id;
} else {
    $admin['city'] = $faker->city;
}
return $admin;
});

Now if I use this factory like bellow:

$user = factory(User::class, $count)->state('Admin')->create();

$user->assignRole('Admin');

Following shows this error:

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

Upvotes: 0

Views: 190

Answers (1)

julianstark999
julianstark999

Reputation: 3616

By passing $count to the factory method $user = factory(User::class, $count)...->create(); you're creating multiple users and the return is a Collection like your Error says.

To assigne the 'Admin' role to each user you have to iterate them

$users = factory(User::class, $count)->state('Admin')->create();

foreach($users as $user)
    $user->assignRole('Admin');

Upvotes: 1

Related Questions