ChrisF79
1 month ago

Unknown Column when inserting into a polymorphic schema

Posted 1 month ago by ChrisF79

I created a "telephonenumbers" table that will store many numbers for each "customer". However, when I try to insert I get an error that the column "phone_number" doesn't exist in the customers table. It doesn't... it's in the telephonenumbers table!

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    protected $guarded = [];

    public function address()
    {
        return $this->morphOne('App\Address', 'addressable');
    }

    public function telephonenumber()
    {
        return $this->morphOne('App\TelephoneNumber', 'telephonenumberable');
    }
}

In my TelephoneNumber.php class

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class TelephoneNumber extends Model
{
    protected $guarded = [];

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

Then I try to insert:

$customer = new App\Customer;
$customer->first_name = "John";
$customer->last_name = "Doe";
$customer->company = "Doe a Deer";
$customer->title = "president";
$customer->website = "laracasts";
$customer->profile_img = "some/url/";

// here's where I'm stuck
$customer->phone_number = "(555) 111-2222";

$customer->save();

This results in:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'phone_number' in 'field list' (SQL: insert into `customers` (`first_name`, `last_name`, `company`, `title`, `website`, `profile_img`, `phone_number`, `updated_at`, `created_at`) values (John, Doe, Doe a Deer, president, laracasts, some/url/, (555) 111-2222, 2020-08-07 00:31:54, 2020-08-07 00:31:54))'

Please sign in or create an account to participate in this conversation.