GianniGianni's avatar

[L5.1] Model Factories and Relationships

I am playing withe the new Model Factory feature, but I don't know how to use relationship in it.

In my project a User has may Status(es) and a Status belongs to a User

This is my ModelFactory.php file:

$factory->define(App\User::class, function ($faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->email,
        'password' => str_random(10),
        'remember_token' => str_random(10),
    ];
});

$factory->define(App\Status::class, function ($faker) {
    return [
        'body' => $faker->sentence,
        'user_id' => /* WHAT DO I WRITE HERE? */,
    ];
});

What do I write for user_id ?

0 likes
6 replies
GianniGianni's avatar

@RachidLaasri If I do like you said, factory will create a new User for every invocation, instead of picking un one randomly

RachidLaasri's avatar

If you want to pick one random user use :

'user_id' => App\User::all()->random()->id,
1 like
GianniGianni's avatar

The best thing would be both things combined together.

I remember I use to do 'user_id' => 'faker:App\User', with TestDummy package

rleger's avatar

Same here, can't find a proper solution.

Did anyone come up with something ?

pmall's avatar

The best thing would be both things combined together.

?

Please or to participate in this conversation.