abkrim
6 months ago
833
6
Laravel

Factories with closure

Posted 6 months ago by abkrim

I am trying to create a factory but I don't achieve my goal.

I need to create users that have a field, scope, that requires creating elements in another table (domains)

These tables do not work with the Laravel model, so I cannot make relationships between them.

  • each user has at least one domain
  • in row scope all domains must in json format
  • a domain can only be one user
$factory->define(App\Models\Albarid\User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => bcrypt('password'), // password
        'remember_token' => Str::random(10),
        'is_super_admin' => false,
        'scope' => json_encode(function () {
            $scope = [];
            $domains = factory(App\Models\Vmail\Domain::class,random_int(2,10))->create();
            foreach ($domains as $domain) {
                $scope[] = $domain->domain;
            }
            return $scope;
        })
    ];
});

DomainFactory

$factory->define(App\Models\Vmail\Domain::class, function (Faker $faker) {
    return [
        'domain' => $faker->unique()->domainName,
        'settings' => 'default_user_quota:1024',
        'albarid_settings' => json_encode( ['default_user_quota' => 1024]),
    ];
});

I know that I have a problem understanding how to work with factories but I can't get it done

Please sign in or create an account to participate in this conversation.