0
votes

I have two models in a Laravel App, Contact and Address which is related to each other.

contacts fields: [id, name] addresses fields: [id, address, contact_id]

In the Contact model, I added :

public function address(){
    return $this->hasOne(Address::class);
}

In the Address model, I added :

public function contact(){
    return $this->belongsTo(Contact::class);
}

I was wondering if it would be ok to interchange the hasOne and belongsTo on the functions, or would it be against any convention that exists.

Like this contacts fields: [id, name, address_id] addresses fields: [id, address]

The reason I am asking this is because I want to create a factory that creates the data on the related tables.

So I would like to generated the seeds of other related tables of contacts like address, role, etc. and get the id during create.

$factory->define(App\Contact::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'address_id' => factory(App\Address::class)->create()->id,
        'other_detail_id' => factory(App\OtherDetail::class)->create()->id
    ];
});
1
Your current definition is okay, don't do it the other way because it will not work.matiaslauriti

1 Answers

-1
votes

First of all, you can still create seeder using factory with current implementation i.e.

$contacts = factory(App\Contact::class, 100)
->create()
->each(function($contact){
    $contact->address()->save(factory(App\Address::class)->make());
}

This code will be placed in seeder of yours, and you will have factories defined for both Contact & Address, and seeder will use the eager relation to do that.