fake()->sentence(), "compan" /> fake()->sentence(), "compan" /> fake()->sentence(), "compan"/>

When using Laravel factories how do I ensure two columns are related?

32 views Asked by At

I have the following factory:

class JobFactory extends Factory
{
    public function definition(): array
    {
        return [
            "title" => fake()->sentence(),
            "company_id" => Company::factory(),
            "contact_id" => Contact::factory(),
        ];
    }
}

Each Contact belongs to a Company, so ideally I'd like the jobs.company_id field to match the contacts.company_id.

Is there an easy way to do this?

1

There are 1 answers

1
IGP On

You can use the factory methods for relationships.

https://laravel.com/docs/11.x/eloquent-factories#belongs-to-relationships

class JobFactory extends Factory
{
    public function definition(): array
    {
        $company = Company::factory();
        $contact = Contact::factory()->for($company, 'company');

        return [
            "title" => fake()->sentence(),
            "company_id" => $company,
            "contact_id" => $contact,
        ];
    }
}