Polymorphic relationship is not inserting type in database

Posted 3 years ago by cullymason

In my app, a Comment can be made by either a User or a Contact. In order to set this up, I created a polymorphic relationship between the three models. However, when I try and save the user to the comment, it never inserts the user_type in the database.

Here is what I have for the insert

    $contact = User::where('email',$email->sender)->first();
    $comment->user->attach($contact);

App\Comment


class Comment extends Model
{
    protected $fillable = ['ticket_id','comment','user_id','comment_type_id','user_type'];
    public function user()
    {
        return $this->morphTo();

    }
}

App\User

class User extends Model 
{

    public function comments()
    {
        return $this->morphMany('App\Comment','user');
    }
}

App\Contact

class Contact extends Model 
{

    public function comments()
    {
        return $this->morphMany('App\Comment','user');
    }
}

My comments table looks like this

comments
    - ticket_id
    - comment
    - user_id
    - user_type
    - comment_type_id

Any idea what is going on?

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