S7327B
S7327B

Reputation: 31

How insert into morph related model in eloquent

Using the laravel ducmunet example :

There are there table like

posts
    id - integer
    title - string
    body - text

videos
    id - integer
    title - string
    url - string

comments
    id - integer
    body - text
    commentable_id - integer
    commentable_type - string

And 3 model (post, command and video) .
Comment model has morphTo relation with post and video.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    /**
     * Get all of the owning commentable models.
     */
    public function commentable()
    {
        return $this->morphTo();
    }
}

class Post extends Model
{
    /**
     * Get all of the post's comments.
     */
    public function comments()
    {
        return $this->morphMany('App\Comment', 'commentable');
    }
}

class Video extends Model
{
    /**
     * Get all of the video's comments.
     */
    public function comments()
    {
        return $this->morphMany('App\Comment', 'commentable');
    }
}

Is there a solution for insert new record into model related to the comment (video or post model).

For example if i have an instace of comment model by this instrument :

$nc = comment::find(3);

Now how can i add new post or video related to $nc comment.

I can't use save method because save method argument is an instance of post or video model but i don't know which model related to $nc comment by polymorphic.


in another word i will add a new post or video to a comment existing ($nc).

Upvotes: 2

Views: 10348

Answers (2)

Bagus Tesa
Bagus Tesa

Reputation: 1695

You could always use associate() and dissociate() just like BelongsTo relation. For example:

$video = Video::find(1);
$comment = new Comment();
$comment->commentable()->associate($video);
$comment->save()

Just a reminder, one comment belongs to a single video or post. Happy coding!

Upvotes: 5

Marcelo Fonseca
Marcelo Fonseca

Reputation: 1844

Improving Bagus answer with the Correct way to use associate()

$video = Video::find(1)

$comment = new Comment();
$comment->commentable()->associate($video);
$comment->save();

Upvotes: 6

Related Questions