I’m working inside a Laravel 9 project and am using model factories. I have User
which can have one Company
.
I need the CompanyFactory
details to be linked to the User
, such as the first name and last name. The user_id
is already mapped with Laravel.
This is my attempt, or what I thought I could do within the CompanyFactory
:
$this->user->first_name
Which is undefined?
Here’s my seeder:
// development seeders
User::factory(2)
->has(Affiliate::factory()->count(50))
->has(Company::factory()->count(1))
->has(Country::factory()->count(3))
->create();
And my CompanyFactory
<?php
namespace DatabaseFactories;
use AppModelsUser;
use AppModelsCountry;
use AppModelsCompany;
use IlluminateDatabaseEloquentFactoriesFactory;
use IlluminateSupportFacadesLog;
use IlluminateSupportFacadesHash;
use IlluminateSupportStr;
use CarbonCarbon;
class CompanyFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Company::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
Log::debug('user', [
'user' => $this->user,
]);
return [
'contact_first_name' => $user->first_name,
'contact_last_name' => $user->last_name ? $user->last_name : null,
'company_name' => $this->faker->company(),
'address_1' => $this->faker->numberBetween(1, 16),
'address_2' => 'Heatherbell Cottages',
'address_3' => null,
'town' => 'Wick',
'county' => 'Caithness',
'postcode' => 'KW14YT',
'telephone_1' => $this->faker->regexify('07[1-57-9]{1}[0-9]{8}'),
'telephone_2' => $this->faker->regexify('07[1-57-9]{1}[0-9]{8}'),
'email' => $user->email,
'bank_name' => $this->faker->word(),
'bank_account_number' => $this->faker->numberBetween(11111111, 99999999),
'bank_sort_code' => $this->faker->numberBetween(111111, 999999),
'bank_iban' => $country ? $this->faker->iban($country->country_code) : null,
'bank_swift' => '',
'ccl_number' => null,
'data_protection_number' => $this->faker->numberBetween(11111111, 99999999),
'currency' => $country ? $country->currency_code : 'GBP',
'notes' => ''
];
}
}
2
Answers
You might have a
belongsTo
relation in theCompany
model.You can use code like this.
OR
https://laravel.com/docs/9.x/eloquent-factories#belongs-to-relationships
Here is a solution I came up with using seeders for my application.