Akshay Khale
Akshay Khale

Reputation: 8361

Laravel: Multiple Polymorphic relationships in a Eloquent Model

I have a Table Named Comments with following structure

Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->morphs('commentable');
$table->morphs('creatable');
$table->text('comment');
$table->timestamps();
});

Eloquent File

class Comment extends Model
{
    public $fillable = ['comment'];

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

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

where I have two polymorphic relationships

commentable for any Article/Post or a Video

creatable for the comment Creator of the comment User/Admin

How to add comment against a Post created by a user?

I tried creating using following code

public function addComment($creatable, $comment)
{
        $this->comments()->create(['comment' => $comment, 'creatable' => $creatable]);
}

It did work, I received following Error

Illuminate/Database/QueryException with message 'SQLSTATE[HY000]: General error: 1364 Field 'creatable_type' doesn't have a default value (SQL: insert into `post_comments` (`comment`, `commentable_id`, `commentable_type`, `updated_at`, `created_at`) values (Test Comment, 1, App/Post, 2018-08-31 10:29:14, 2018-08-31 10:29:14))'

Thanks in advance!!!

Upvotes: 4

Views: 3477

Answers (1)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

You can use make():

public function addComment($creatable, $comment)
{
        $this->comments()->make(['comment' => $comment])
            ->creatable()->associate($creatable)
            ->save();
}

Upvotes: 6

Related Questions