It seems you should use for() method:
$application = Application::create([ ... ]);
Referrer::factory()->for($application)
https://laravel.com/docs/12.x/eloquent-factories#belongs-to-relationships
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I’m using a model (application) which has two hasOne models (applicant and referrer) linked to it.
So the application table has applicant_id and referrer_id and both the linked to tables have application_id
In the seeder I create the application, but how do I pass the ID of the application to the factories for referrer and applicant?
I’m very new here, so assume I’m wrong / ignorant
Thanks all
@pgogy I think your issue is stemming from you thinking you need to put foreign keys in both tables. You don’t. It’s impossible to define a cyclical relationship like that as you can’t insert one record without pointing to the other, and that other record can’t be created without the initial record being created first.
So if you are wanting to create individual tables and models for applicants and referrers then do so, and put the foreign keys in your applications table:
Schema::create('applications', function (Blueprint $table) {
$table->id();
$table->foreignId('applicant_id')->constrained()->cascadeOnDelete();
$table->foreignId('referrer_id')->constrained()->cascadeOnDelete();
// Other application table columns...
});
Schema::create('applicants', function (Blueprint $table) {
$table->id();
// Applicant-specific columns...
});
Schema::create('referrers', function (Blueprint $table) {
$table->id();
// Referrer-specific columns...
});
Then define your model relations:
class Application extends Model
{
public function applicant(): BelongsTo
{
return $this->belongsTo(Applicant::class);
}
public function referrer(): BelongsTo
{
return $this->belongsTo(Referrer::class);
}
}
class Applicant extends Model
{
public function applications(): HasMany
{
return $this->hasMany(Application::class);
}
}
class Referrer extends Model
{
public function applications(): HasMany
{
return $this->hasMany(Application::class);
}
}
Like my previous answer, you’d then be able to use your ApplicationFactory to create application models in a seeder:
class ApplicationFactory extends Factory
{
public function definition(): array
{
return [
'applicant_id' => Applicant::factory(),
'referrer_id' => Referrer::factory(),
];
}
}
class ApplicantSeeder extends Seeder
{
public function run(): void
{
Application::factory()->create();
}
}
Please or to participate in this conversation.