Polymorphic One to Many relationship is NULL

Viewed 140

I'm working on a Laravel project with subdomains. Each new company gets it own subdomain. Every client that is created inside a company needs to get the same subdomain.

Because it's possible that a subdomain will change over time I'm using a subdomain table.

So I have three tables and models: Subdomain, Company and Client and the following rules:

  • A subdomain can have multiple organisations (Company or Client)
  • A Company can have one subdomain
  • A client can have one subdomain

Therefore I'm using a polymorphic One to Many relationship.

create_subdomains_table Migration

Schema::create('subdomains', function (Blueprint $table) {
    $table->id();
    $table->string('name')->unique();
    $table->morphs('organisation');
    $table->timestamps();
});

create_companies_table Migration

Schema::create('companies', function (Blueprint $table) {
    $table->id();
    $table->string('enterprise_number')->unique();
    $table->string('legal_entity_type');
    $table->string('business_name');
    $table->string('phone');
    $table->string('email');
    $table->json('ancestry')->nullable();
    
    $table->bigInteger('subdomain_id')->unsigned()->nullable();
    $table->foreign('subdomain_id')->references('id')->on('subdomains');

    $table->timestamps();
});

Company Model

public function subdomain() {
    return $this->morphOne(Subdomain::class, 'organisation');
}

Subdomain Model

public function organisation() {
    return $this->morphTo();
}

Create company controller function

// Create subdomain
$subdomain = Subdomain::create([
    'name' => Str::slug($validatedData['business_name'], '-')
]);

// Create company
$company = Company::create([
    'enterprise_number' => $validatedData['enterprise_number'],
    'legal_entity_type' => $validatedData['legal_entity_type'],
    'business_name' => $validatedData['business_name'],
    'phone' => $validatedData['phone'],
    'email' => $validatedData['email'],
]);

// Create relationship between company and subdomain
$company->subdomain()->save($subdomain);

This results in an error Not null violation: 7 ERROR: null value in column \"organisation_type\" of relation \"subdomains\" violates not-null constraint

Although I found $table->morphs('organisation'); in the Laravel documentation I changed it to

$table->bigInteger('organisation_id')->unsigned()->nullable();
$table->string('organisation_type')->nullable();

This works to create a subdomain and company entry but the subdomain_id column in the companies table is NULL.

What did I do wrong?

1 Answers

'enterprise_number' => should the model id ex: 1,
'legal_entity_type' => should the model namespace ex: 'App\Models\ModelName',

Related